Detect variance on generic type parameters of interfaces
Is there a way to refl开发者_Python百科ect on an interface to detect variance on its generic type parameters and return types? In other words, can I use reflection to differentiate between the two interfaces:
interface IVariant<out R, in A>
{
R DoSomething(A arg);
}
interface IInvariant<R, A>
{
R DoSomething(A arg);
}
The IL for both looks the same.
There is a GenericParameterAttributes Enumeration that you can use to determine the variance flags on a generic type.
To get the generic type, use typeof
but omit the type parameters. Leave in the commas to indicate the number of parameters (code from the link):
Type theType = typeof(Test<,>);
Type[] typeParams = theType.GetGenericArguments();
You can then examine the type parameters flags:
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;";
}
}
精彩评论