C#中没有Java通配符。在Java中,类型类型是
Class<T>其中
T的类本身。C#中的等效项是类型
Type,它 不是泛型的
。因此,您似乎最好的办法就是拥有一个
Dictionary<Type,int>,如果将其封装在一个类中,则可以限制您在代码中放入字典的内容(因此,这只是运行时检查):
private Dictionary<Type, int> myDictionary = new Dictionary<Type, int>();public void Add(Type type, int number) { if (!typeof(baseClass).IsAssignableFrom(type)) throw new Exception(); myDictionary.Add(type, number);}您甚至可以
IDictionary使用该逻辑来实现自己的逻辑。
更新
我可以想到的另一个 运行时 技巧是为您的类型使用包装器类:
public class TypeWrapper<T>{ public Type Type { get; private set; } public TypeWrapper(Type t) { if (!typeof(T).IsAssignableFrom(t)) throw new Exception(); Type = t; } public static implicit operator TypeWrapper<T>(Type t) { return new TypeWrapper<T>(t); }}(也可以执行
Equals和
GetHashCode,仅委托给
Type。)
然后您的字典变成:
var d = new Dictionary<TypeWrapper<baseClass>, int>();d.Add(typeof(baseClass), 2);d.Add(typeof(Child), 3);



