简体   繁体   中英

Generic type definition subtype doesn't reflect as such

Given

public class Generic<T> {}
public class SubGeneric<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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM