[英]Generic type paramaters are not types?
I find the following a bit confusing....我发现以下内容有点令人困惑......
Dictionary<Type, Object> _typeMap;
public void RegisterType<T>(Object o)
{
_typeMap.Add(typeof(T), o);
}
Why is typeof(T)
required in the Add
method?为什么在
Add
方法中需要typeof(T)
? Isn't the T
type paramater already a Type
? T
类型参数不是已经是Type
了吗? What else is it?还有什么?
T
is a type name , and typeof
is used to retrieve the corresponding Type
object. T
是一个类型名称, typeof
用于检索对应的Type
object。
A generic type parameter works exactly like just any other type name, say, int
.泛型类型参数的工作方式与任何其他类型名称完全相同,例如
int
。 You can't exactly do typeMap.Add(int, 0);
你不能完全做
typeMap.Add(int, 0);
either.任何一个。
No. Add
here needs an instance of a Type
class .不,在这里
Add
需要一个Type
class 的实例。
Generic type parameters are not instances of Type
class.泛型类型参数不是
Type
class 的实例。
You hace to put the typeof(T) because T is the class definition, and the type is an object describing a Type, that for T and for Object and for String... etc etc.您必须输入 typeof(T) 因为 T 是 class 定义,并且类型是描述类型的 object ,用于 T 和 Object 等。
typeof gets the Type of the class definition. typeof 获取 class 定义的类型。
This solution strikes me as aa bit of an "opps".这个解决方案让我觉得有点“opps”。 I believe that the result of the this code will always be to try to add an entry with key "Type" into the dictionary due to the fact that you are always get the "typeof" of a Type .
我相信此代码的结果将始终是尝试将带有键“Type”的条目添加到字典中,因为您总是得到Type的“typeof”。 Instead I think what you are looking for is...
相反,我认为你正在寻找的是......
public void RegisterType<T>(Object o)
{
_typeMap.Add(T, o);
}
Hope it helps!希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.