Dispersion detection by typical interface type parameters

Is there a way to think about an interface for detecting variance by its typical type parameters and return types? In other words, is it possible to use reflection to distinguish between two interfaces:

interface IVariant<out R, in A> { R DoSomething(A arg); } interface IInvariant<R, A> { R DoSomething(A arg); } 

IL for both looks the same.

+4
source share
1 answer

There is a GenericParameterAttributes Enumeration that you can use to define dispersion flags for a generic type.

To get a generic type, use typeof , but omit the type parameters. Leave it in commas to indicate the number of parameters (code from the link):

 Type theType = typeof(Test<,>); Type[] typeParams = theType.GetGenericArguments(); 

Then you can check the flags of type parameters:

 GenericParameterAttributes gpa = typeParams[0].GenericParameterAttributes; GenericParameterAttributes variance = gpa & GenericParameterAttributes.VarianceMask; string varianceState; // Select the variance flags. if (variance == GenericParameterAttributes.None) { varianceState= "No variance flag;"; } else { if ((variance & GenericParameterAttributes.Covariant) != 0) { varianceState= "Covariant;"; } else { varianceState= "Contravariant;"; } } 
+6
source

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


All Articles