gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:54:47 24 4
gpt4 key购买 nike

我有一个名为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com