我不知道该怎么做...
我有一个执行各种功能的类:
public abstract class EntityBase { ... }
public interface ISomeInterface<T> where T : EntityBase, new() { ... }
public class SomeClass<T> : ISomeInterface<T> { ... }
我试图在非通用类中缓存这些:
public class MyClass
{
//Not sure how to do this
private ConcurrentDictionary<?, ISomeInterface<?>> Cache { get; set; }
}
问题是 EntityBase 是抽象的,不能执行 new(),ISomeInterface 需要一个基于 EntityBase 并执行 new() 的类。有什么办法可以做我想做的事吗?
更新:我意识到对于 TKey 我可以使用 Type,但我仍然不确定为 ISomeInterface 添加什么。
最佳答案
首先,我认为您打算使用 ConcurrentDictionary
,因为您有一个键/值对。
其次,你可以像 ICloneable 那样做。 ICloneable 有一个返回 Object
而不是 T 的方法。
private ConcurrentDictionary<Type, Object> Cache { get; set; }
由于它是私有(private)的,您可以在内部管理它并根据需要进行转换。显然,您必须确保任何函数调用都具有类型参数定义,例如:
//I omitted error checking on all the examples.
public class Foo : EntityBase { ... }
void DoSomething<Foo>()
{
var someClass = Cache[typeof(Foo)] as ISomeInterface<Foo>
someClass.Bar();
}
此外,即使该属性有另一个修饰符(公共(public)、内部、 protected ),您也可以向调用者添加注释,说明该对象是 ISomeInterface 的泛型类型,其中 T 是 EntityBase、new()。然后,他们只需按需要转换即可。
您还可以在非泛型类上使用泛型方法来将缓存项作为泛型类型获取:
ISomeInterface<T> GetInstance<T>()
where T : EntityBase, new()
{
return Cache[typeof(T)] as ISomeInterface<T>;
}
void AddInstance<T>(ISomeInterface<T> instance)
where T : EntityBase, new()
{
Cache[typeof(T)] = instance;
}
void DoSomething<T>()
{
var someClass = GetInstance<T>();
someClass.Bar();
}
关于c# - 非通用类中的通用属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6738962/