Get type of nested common class in Generic class in C #

In my project, I use the following class: Filter<T>.Checker<U> , which also has an IChecker interface. It looks like this:

 class Filter<T> { public interface IChecker { ... } public class Checker<U> : IChecker { ... } List<IChecker> checkers; ... } 

The Filter class filters objects of type T. The filter uses the IChecker list to check various fields in class T, in which U is the type of this field in T.

In another method in another class, I want to instantiate a validation. In this method, type T is a transaction that is known at compile time. Type U is known only by an instance of the type. The code below shows how you usually create an instance of a generic class, knowing the type.

 Type type = typeof(MyObject<>).MakeGenericType(objectType); object myObject = Activator.CreateInstance(type); 

I want to do this a little further and do the following:

 Type type = typeof(Filter<Transaction>.Checker<>).MakeGenericType(objectType); object myObject = Activator.CreateInstance(type); 

The typeof(Filter<Transaction>.Checker<>) part typeof(Filter<Transaction>.Checker<>) does not compile. The compiler says: Unexpected use of an unbounded generic name .

Is it possible to get a nested common class type in a Generic class in C #?

+6
source share
2 answers

Well, generics require you to specify all or not common arguments. Since you do not know the second argument at compile time, you must pass both of them as arguments to MakeGenericType :

 Type type = typeof(Filter<>.Checker<>).MakeGenericType(typeof(Transaction), objectType); object myObject = Activator.CreateInstance(type); 

Although at compile time you know the type of Transaction , you need to specify through typeof() , but this should not hurt.

I checked with the is operator that type arguments are applied in the expected order.

+3
source

I think you need to omit the first general parameter T here and pass both types as an array:

 Type type = typeof(Filter<>.Checker<>).MakeGenericType(typeof(Transaction),objectType); 
+4
source

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


All Articles