开发者

Comparing types

I have a Generic method where I need to compare the generic type with another type.

The following code always throws the exception:

if (!(开发者_JAVA百科_vertexType.DataType is T))
   throw new Exception();

But this doesn't:

if(_vertexType.DataType != default(T).GetType())
   throw new Exception();

Why is this? Is there something about the is operator I don't understand?

If it helps, the _vertexType.DataType function looks like this:

Type DataType
{
   get { return default(myType).GetType(); }
}

Tips on how to do it properly would be great too.


The type of a Type is the class named Type, not what it points to. (Hope that made sense!) So you're really checking if the Type object representing Type is equal to some other Type object, and it obviously isn't.

In other words, saying

_vertexType.DataType is T

is like saying

typeof(T).IsAssignableFrom(_vertexType.DataType.GetType())

but it's obviously not normally true, since calling GetType() on a Type object gives you a Type object representing the Type class.


Use typeof(myType) instead of the default(myType).GetType(). Also your DataType is already returning a Type, so you should be using comparison:

if(_vertexType.DataType != typeof(T))
   throw new Exception();

The DataType property is already returning an instance of Type, so the only time _vertexType.DataType is T will be true is when T is Type.


_vertexType.DataType will only ever be T when T is of type Type, based on your property declaration.


This code:

_vertexType.DataType != default(T).GetType()

will always throw a System.NullReferenceException if T is a reference type. It will work for value types and structs, because these can't be null and have default values which provides an instance to call GetType() on.

The default keyword here is basically syntactic sugar (for null for reference types and the default value for value types) and translates into an IL OpCode of

initobj !!T

which, according to the documentation initialises values type with null references and the default values of primitive types. This also seems to include generic reference types.

See: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜