c# - 非通用类中的通用属性?

标签 c# generics collections dictionary constraints

我不知道该怎么做...

我有一个执行各种功能的类:

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/

相关文章:

java - Collections.binarySearch 是如何工作的?

c# - 如何计算数组中的事件线程并避免 "collection was modified"错误?

c# - Firebird 在 .NET 中发送所有事件

c# - 如何打开测试项目代码文件夹中的文件? (Visual Studio 2008 和 .NET C#)

java - java中如何将对象集合作为方法的参数传递

java - 正确使用java泛型?

c# - 即使集合没有改变,MVVM 从 ViewModel 刷新 Datagrid

c# - 如何呈现不同于填充 XNA 的立方体的特定边缘? (单人游戏)

java - 在 Java 中隐藏一个 "local"类型参数

c# - Linq to NHibernate 返回名称以字符串列表内容开头的实体