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

发布于 2024-09-02 02:47:44 字数 236 浏览 2 评论 0原文

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

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


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

两者的 IL 看起来相同。

Is there a way to reflect 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

计㈡愣 2024-09-09 02:47:44

您可以使用 GenericParameterAttributes 枚举确定泛型类型的差异标志。

要获取泛型类型,请使用 typeof 但省略类型参数。保留逗号以指示参数数量(来自链接的代码):

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

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

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;";
    }
}

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;";
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文