繁体   English   中英

保持字典 <Type, MyClass<T> &gt;哪些元素可按类型引用

[英]Keep a Dictionary<Type, MyClass<T>> where elements are referenceable by type

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

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();

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

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>;
   }
}

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

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

您可以使用非泛型的接口,然后在该抽象类中显式实现该接口,这在.Net库本身中非常常见:

public interface IEntityTypeTransform
{
    Func<IDataRecord, object> GetDataTransform();
}

public abstract class EntityTypeTransform<TEntityType> : IEntityTypeTransform
    where TEntityType : class
{
    public virtual Func<IDataRecord, TEntityType> GetDataTransform()
    {
        return this.GetDataTransformImpl();
    }

    public abstract Func<IDataRecord, TEntityType> GetDataTransformImpl();

    Func<IDataRecord, object> IEntityTypeTransform.GetDataTransform()
    {
        return this.GetDataTransform();
    }
}

您必须创建一个非泛型基类,例如

public abstract class EntityTypeTransformBase
{
    public abstract Func<IDataRecord, object> GetDataTransform();
}

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

    public override Func<IDataRecord, object> GetDataTransform()
    {
        return GetDataTransformImpl();
    }
}

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

现在您可以创建您的字典:

var d = new Dictionary<Type, EntityTypeTransformBase>();
d.Add(typeof(TaskParameter), new TaskParameterEntityTypeTransform());

您可以使用KeyedByTypeCollection来获取类型安全性,并且可以使用协变类型参数定义接口,以确保只能将类型为EntityTypeTransform<T>对象添加到字典中:

public interface IEntityTypeTransform<out TEntityType> where TEntityType : class
{
    TEntityType Transform(IDataRecord dataRecord);
}

public abstract class EntityTypeTransform<TEntityType> : IEntityTypeTransform<TEntityType> where TEntityType : class
{
    public abstract TEntityType Transform(IDataRecord dataRecord);
}

public class TaskParameter
{
    public int TaskId;
    public string Name;
    public string Value;
}

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

public class SomeClass
{
    public KeyedByTypeCollection<IEntityTypeTransform<object>> TransformDictionary = new KeyedByTypeCollection<IEntityTypeTransform<object>>()
    {
        new TaskParameterEntityTypeTransform(),
        // More transforms here
    };
}

现在您可以像这样使用它:

public void SomeMethod(IDataRecord dataRecord)
{
    TaskParameter taskParameter = TransformDictionary.Find<TaskParameterEntityTypeTransform>().Transform(dataRecord);
}

为变换器添加非通用接口:

public interface IEntityTypeTransform
{
    Func<IDataRecord, object> GetDataTransform();
}
public abstract class EntityTypeTransform<T> : IEntityTypeTransform
{
    public abstract Func<IDataRecord, object> GetDataTransform();
}
public class TaskParameterEntityTypeTransform : EntityTypeTransform<TaskParameter>
{
    public override Func<IDataRecord, object> GetDataTransform()
    {
        return dataRecord => new TaskParameter()
        {
            TaskId = (int)dataRecord["task id"],
        };
    }
}

然后,您可以封装字典以确保数据类型始终匹配。 永远不允许添加错误类型的IEntityTypeTransform:

public class TransformDistributor
{
    private readonly Dictionary<Type, IEntityTypeTransform> _transforms = new Dictionary<Type, IEntityTypeTransform>();
    public void Add<T>(EntityTypeTransform<T> type)
    {
        this._transforms.Add(typeof(T), type);
    }
    public T Transform<T>(IDataRecord record)
    {
        var transform = this._transforms[typeof(T)].GetDataTransform()(record);
        if (transform is T)
        {
            return (T)transform;
        }
        else
        {
            // theorically can't happen
            throw new InvalidOperationException("transformer doesn't return instance of type " + transform.GetType().Name);
        }
    }
}

优点是在编译时,即使您没有使用泛型,也确保没有人可以插入坏变压器。

用法:

var transforms = new TransformDistributor();
transforms.Add<TaskParameter>(new TaskParameterEntityTypeTransform());

var taskParameter = transforms.Transform<TaskParameter>(new DataRecord());

我试图了解你到底想要什么,我希望这正是你所寻找的!

您应在TaskParameter类中设置正确的参数:TaskId,Name,Value

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 x => new TaskParameter { X = x.FieldCount };
  }
}

public class TaskParameter
{
  public int X { get; set; }
}

Dictionary<Type, EntityTypeTransform<TaskParameter>> imADict;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM