保持字典<Type,MyClass <T >>,其中元素可按类型引用

Stu*_*eks 14 c# generics dictionary

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

public abstract class EntityTypeTransform<TEntityType> where TEntityType : class
{
    public abstract Func<IDataRecord, TEntityType> GetDataTransform();
}
Run Code Online (Sandbox Code Playgroud)

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

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"]
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Dictionary<Type, EntityTypeTransform<T>>
Run Code Online (Sandbox Code Playgroud)

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

谁能帮我吗?

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

Tho*_*que 9

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

例如,您可以像这样实现缓存:

static class TransformCache<TEntityType>
{
    public static EntityTypeTransform<TEntityType> Transform { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

TransformCache<TaskParameter>.Transform = new TaskParameterEntityTypeTransform();
Run Code Online (Sandbox Code Playgroud)


dec*_*cPL 5

您不能指定包含不同泛型类型的强类型集合.这是我在类似问题中使用的方法,经过修改以符合您的要求:

class TransformCollection
{
   private Hashtable cache = new Hashtable();

   public void Add<T>(EntityTypeTransform<T> transform) where T : class
   {
      this.cache[typeof(T)] = itemToCache;
   }

   public bool Exists<T>() where T : class
   {
      return this.cache.ContainsKey(typeof(T));
   }

   public EntityTypeTransform<T> Get<T>() where T : class
   {
      if (!this.Exists<T>())
         throw new ArgumentException("No cached transform of type: " + typeof(T).Name);
      return this.cache[typeof(T)] as EntityTypeTransform<T>;
   }
}
Run Code Online (Sandbox Code Playgroud)

这为您的泛型类型提供了类型安全的缓存(尽管类的安全性是由类的逻辑强制执行的,而不是C#).您可以按如下方式使用它:

var collection = new TransformCollection();
collection.Add(SomeMethodToGetTransform<Task>());
//...
if (collection.Exists<Task>())
{
   var transform = collection.Get<Task>();
   //...
}
Run Code Online (Sandbox Code Playgroud)