c# - 保留一个 Dictionary<Type, MyClass<T>> ,其中元素可以按类型引用

标签 c# generics dictionary

我有一个名为 EntityTypeTransform 的抽象类,它有一个抽象方法,用于保存将 IDataRecord 转换为 T 实例的 Func 委托(delegate)。

public abstract class EntityTypeTransform<TEntityType> where TEntityType : class
{
    public abstract Func<IDataRecord, TEntityType> GetDataTransform();
}

该类的实现可能看起来像(看起来像):

public class TaskParameterEntityTypeTransform : EntityTypeTransform<TaskParameter>
{
    public override Func<IDataRecord, TaskParameter> GetDataTransform()
    {
        return dataRecord => new TaskParameter()
        {
            TaskId = (int)dataRecord["task_id"],
            Name = (string)dataRecord["p_name"],
            Value = (string)dataRecord["p_value"]
        };
    }
}

现在我想在通用字典中保留每个类的实例,例如:

Dictionary<Type, EntityTypeTransform<T>>

但这不起作用,因为(例如)EntityTypeTransform Of Task 的实例与 EntityTypeTransform Of TaskParameter 的实例不同。

谁能帮帮我?

编辑:我应该添加 Type key = typeof(T)

最佳答案

实际上,您根本不需要使用字典!您可以使用 GenericClass<T> 的事实对于每个 T 实际上是不同的类型,因此它可以有自己的静态字段(即 GenericClass<Foo>.SomeField 不与 GenericClass<Bar>.SomeField 共享)

例如你可以这样实现你的缓存:

static class TransformCache<TEntityType>
{
    public static EntityTypeTransform<TEntityType> Transform { get; set; }
}

然后像这样使用它:

TransformCache<TaskParameter>.Transform = new TaskParameterEntityTypeTransform();

关于c# - 保留一个 Dictionary<Type, MyClass<T>> ,其中元素可以按类型引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19543971/

相关文章:

Java:所有派生类必须实现的抽象或通用列表

C#.NET 泛型方法和继承

python - 从包含字典列表的系列创建 pandas 数据框

c# - 在网络网格中将数据显示为链接

c# - 无法访问其他项目中的公共(public)类,但具有相同的命名空间

c# - C# 中的泛型和函数

python - 从字典中调用方法?

c# - Web 浏览器控件 : Navigation to the webpage was canceled

c# - 如何使我的字符串属性可为空?

C++ 模板类重载 [] 运算符