C#的相当于Java的通配符 [英] C#'s equivalent of Java's wildcard
问题描述
如果它存在,什么是C#相当于下面的Java代码:
If it exists, what is the C# equivalent of the following Java code:
new HashMap<Class<? extends BaseClass>, Integer>();
我目前使用新字典<类型,INT>()
,这更像是
新的HashMap<类<>中整数方式>()
这显然是不一样的。
I currently use new Dictionary<Type, int>()
, which is more like
new HashMap<Class<?>, Integer>()
which is obviously not the same.
的(忽略的HashMap
之间的差异和词典
)
(Ignore the differences between HashMap
and Dictionary
)
修改:要澄清,我不是试图定义一个新的类,只需创建一个实例的HashMap
/ 词典
。
To clarify, I am not trying to define a new class, simply create an instance of HashMap
/Dictionary
.
推荐答案
没有在C#中的Java通配符的当量。在Java中,类型的类型是类< T>
,其中 T
是类本身。在C#中的等价物的类型是键入
,其中的不是泛型的。如此看来,你能做的最好是有,如你所说,一个词典<类型,INT>
,如果它封装在一个类中,你可以限制你摆在字典中的代码(因此它只是一个运行时检查):
There is no equivalent of the Java wildcard in C#. In Java, the type for types is Class<T>
where T
is the class itself. The equivalent in C# is the type Type
, which is not generic. So it seems that the best you can do is to have, as you said, a Dictionary<Type, int>
, and if it's encapsulated in a class you can restrict what you put in the dictionary in the code (so it will just be a runtime check):
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
与逻辑。
You can even implement your own IDictionary
with that logic.
更新
另外的运行的把戏我能想到的是使用包装类的类型:
Another runtime trick I can think of is to use a wrapper class for your types:
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);
}
}
(也实现等于
和的GetHashCode
,只委托给键入
)
然后你的字典里就变成了:
And then your dictionary becomes:
var d = new Dictionary<TypeWrapper<BaseClass>, int>();
d.Add(typeof(BaseClass), 2);
d.Add(typeof(Child), 3);
这篇关于C#的相当于Java的通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!