检测接口的泛型类型参数的方差

Wat*_* v2 4 .net reflection covariance contravariance variance

有没有办法反映一个接口来检测其泛型类型参数和返回类型的差异?换句话说,我可以使用反射来区分两个接口:

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


interface IInvariant<R, A>
{
   R DoSomething(A arg);
}
Run Code Online (Sandbox Code Playgroud)

两者的IL看起来都一样.

Sim*_*ens 6

有一个GenericParameterAttributes枚举,您可以使用它来确定泛型类型的方差标志.

要获取泛型类型,请使用typeof但省略类型参数.留下逗号表示参数数量(链接中的代码):

Type theType = typeof(Test<,>);
Type[] typeParams = theType.GetGenericArguments();
Run Code Online (Sandbox Code Playgroud)

然后,您可以检查类型参数标志:

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;";
    }
}
Run Code Online (Sandbox Code Playgroud)