You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助泛型将接口转换为派生类型(Dictionary序列化场景)

解决方案

方案1:扩展IEntityTable接口(推荐)

如果可以修改IEntityTable接口,直接添加一个非泛型的序列化方法,就能完全避免反射,代码更简洁高效:

// 修改IEntityTable接口
public interface IEntityTable
{
    // 添加非泛型序列化方法
    object Serialize();
}

// 在EntityTable<T>中实现该方法
public class EntityTable<T> : IEntityTable
{
    // 原有的泛型序列化逻辑可保留
    public string SerializeGeneric()
    {
        // 你的序列化实现,比如返回JSON字符串或其他格式
        return JsonSerializer.Serialize(this);
    }

    // 实现IEntityTable的非泛型方法
    public object Serialize()
    {
        return SerializeGeneric();
    }
}

之后直接遍历字典调用即可,无需反射:

var serializedData = new List<object>();
foreach (var kvp in dictionary)
{
    serializedData.Add(kvp.Value.Serialize());
}

方案2:使用反射(无法修改接口时)

如果不能修改IEntityTable接口,就用反射来获取并调用具体EntityTable<T>的Serialize方法:

var serializedData = new List<object>();
// 获取EntityTable<T>的泛型类型定义
var entityTableGenericDef = typeof(EntityTable<>);

foreach (var kvp in dictionary)
{
    // 构造当前键对应的具体EntityTable<T>类型
    var concreteType = entityTableGenericDef.MakeGenericType(kvp.Key);
    
    // 验证值是否属于该类型(可选,避免类型不匹配错误)
    if (!concreteType.IsInstanceOfType(kvp.Value))
        continue;
    
    // 获取Serialize方法(假设方法无参数)
    var serializeMethod = concreteType.GetMethod("Serialize", Type.EmptyTypes);
    if (serializeMethod == null)
        continue;
    
    // 调用Serialize方法并收集结果
    var serializedResult = serializeMethod.Invoke(kvp.Value, null);
    serializedData.Add(serializedResult);
}

注意事项

  • 如果Serialize方法有参数,需要在GetMethod中传入对应的参数类型数组。
  • 若需要频繁执行这段逻辑,建议缓存反射获取的MethodInfo,避免重复反射带来的性能开销。

内容的提问来源于stack exchange,提问作者WDUK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:28:11