开发者

Generic type definition subtype doesn't reflect as such

Given

public class Generic<T> {}
public class SubGener开发者_如何学Cic<T> : Generic<T> {}

All the following are false:

typeof(Generic<>).IsAssignableFrom(typeof(SubGeneric<>));
typeof(SubGeneric<>).IsSubclassOf(typeof(Generic<>));
typeof(SubGeneric<>).BaseType.Equals(typeof(Generic<>));

The first makes sense (until concrete they aren't assignable). But why this behavior on the other two?


SubGeneric<T> inherits Generic<T>, not Generic<>

Had it inherited Generic<>, it wouldn't convey enough information.
Consider the difference between

class Wierd<T1, T2> : Generic<T1> { }

and

class Wierd<T1, T2> : Generic<T2> { }

or even

class Wierd<T1, T2> : Generic<Wierd<T2, T1>> { }

The BaseType includes the specific parameterization of the base type.

typeof(SubGeneric<>).BaseType.GetGenericArguments() will return an array containing SubGeneric<>'s generic type parameter (<T>).


typeof(SubGeneric<>).BaseType.GetGenericTypeDefinition() == typeof(Generic<>);

should be true.


I think these assertions make no sense until a T is given.

SubGeneric<T> is a subclass of Generic<T> but SubGeneric<> and Generic<> (without any T) aren't classes at all and cannot derive one from each other, or that may mean that any SubGeneric<U> could be a subclass of Generic<V>, which obviously is incorrect.


I think it is to do with the generic parameter.

SubGeneric<string> is not a subclass of Generic<int>

So without knowing about the generic parameter, an inference cannot be made.

typeof(SubGeneric<int>).IsSubclassOf(typeof(Generic<int>));
typeof(SubGeneric<string>).BaseType.Equals(typeof(Generic<string>));

should return true.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜