开发者

Generic type paramaters are not types?

I find the following a bit confusing....

Dictionary<Type, Object> _typeMap;

public void开发者_StackOverflow社区 RegisterType<T>(Object o)
{
    _typeMap.Add(typeof(T), o);
}

Why is typeof(T) required in the Add method? Isn't the T type paramater already a Type? What else is it?


T is a type name, and typeof is used to retrieve the corresponding Type object.

A generic type parameter works exactly like just any other type name, say, int. You can't exactly do typeMap.Add(int, 0); either.


No. Add here needs an instance of a Type class.

Generic type parameters are not instances of 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 gets the Type of the class definition.


This solution strikes me as a a bit of an "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. Instead I think what you are looking for is...

public void RegisterType<T>(Object o)
{
    _typeMap.Add(T, o);
}

Hope it helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜