I have a generic class and a derived class as following.
public class GenericClass<T> { ... } public class DerivedClass : GenericClass<SomeType> { ... }
How do I find the derived class via reflection? I have tried both ways below, but doesn't seem to work.
System.Reflection.Assembly.GetExecutingAssembly().GetTypes().Where(t => typeof(GenericClass<>).IsAssignableFrom(t)); System.Reflection.Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsSubclassOf(typeof(GenericClass<>));
A generic type is a class or interface that is parameterized over types. We use angle brackets (<>) to specify the type parameter.
Generic Class T is called type parameter, which can be used as a type of fields, properties, method parameters, return types, and delegates in the DataStore class. For example, Data is generic property because we have used a type parameter T as its type instead of the specific data type.
In the same way, you can derive a generic class from another generic class that derived from a generic interface. You may be tempted to derive just any type of class from it. One of the features of generics is that you can create a class that must implement the functionality of a certain abstract class of your choice.
var result = System.Reflection.Assembly.GetExecutingAssembly() .GetTypes() .Where(t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof(GenericClass<>));
It's a bit more complex than that. t.BaseType may return null (e.g. when t is an interface). Also note that the Type.IsSubclassOf method does not work for generic types! If you are dealing with a generic type you should use the GetTypeDefinition method. I recently blogged about how to get all derived types of a class. Here's an IsSubclass method that works for generics, too:
public static bool IsSubclassOf(Type type, Type baseType) { if (type == null || baseType == null || type == baseType) return false; if (baseType.IsGenericType == false) { if (type.IsGenericType == false) return type.IsSubclassOf(baseType); } else { baseType = baseType.GetGenericTypeDefinition(); } type = type.BaseType; Type objectType = typeof(object); while (type != objectType && type != null) { Type curentType = type.IsGenericType ? type.GetGenericTypeDefinition() : type; if (curentType == baseType) return true; type = type.BaseType; } return false; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With