在C#中沒有等效的Java通配符。在Java中,類型的類型是Class<T>
,其中T
是類本身。在C#中的等效項是Type
,其中不是通用的。所以看起來你所能做的最好的就是像你說的那樣擁有一個,如果它封裝在一個類中,你可以限制你在代碼中放入字典中的東西(所以它只是一個運行時檢查):
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
。
UPDATE
另一個運行招我能想到的是使用包裝類的類型:(還實現Equals
和GetHashCode
,只是委託給Type
)
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);
}
}
然後你的字典變成:
var d = new Dictionary<TypeWrapper<BaseClass>, int>();
d.Add(typeof(BaseClass), 2);
d.Add(typeof(Child), 3);
可能重複的http://計算器。com/questions/4732494/cs-javas-equivalent-of-javas-extend-base-in-generics – halex
@halex我看到了這個問題,它很相似 - 但它絕對不一樣。 – Acidic