Find type, given base type and implemented type

Here is what I have.

BaseClass<T> { } MyClass { } NewClass : BaseClass<MyClass> { } 

I need to find out if there is a class that implements BaseClass with a specific common implementation of MyClass and gets the type of this class. In this case it will be NewClass

Edit

 AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where( typeof(BaseClass<>).MakeGenericType(typeof(MyClass)).IsAssignableFrom); 

Returns a list of all types that implement BaseClass <MyClass>.

thanks

+4
source share
1 answer

If you have a list of types (called types ) that you want to test, you can get all types that inherit from the specified base class using the IsAssignableFrom method:

 var baseType = typeof(BaseClass<MyClass>); var info = types.Where(t => baseType.IsAssignableFrom(t)).FirstOrDefault(); if (info != null) // We have some type 'info' which matches your requirements 

If you only have runtime information of type MyClass , you can get baseType like this:

 Type myClassInfo = // get runtime info about MyClass var baseTypeGeneric = typeof(BaseClass<>); var baseType = baseTypeGeneric.MakeGenericType(myClassInfo); 

You wrote that you need to find the class somehow, so the final question is how to get the types list. To do this, you will need to find several assemblies - you can start with the currently executing assembly (if the type is in your application) or using the well-known assembly identified by its name.

 // Get all types from the currently running assembly var types = Assembly.GetExecutingAssembly().GetTypes(); 

Unfortunately, there is no way to β€œmagically” find a type like this: you will need to search for all available types, which can be quite an expensive operation. However, if you need to do this only once (for example, when starting the application), you should be fine.

+5
source

Source: https://habr.com/ru/post/1311534/


All Articles