如何验证是否型重载/支持某运营商? [英] How to verify whether a type overloads/supports a certain operator?

查看:116
本文介绍了如何验证是否型重载/支持某运营商?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检查某个类型是否实现了一定的经营者?

 结构CustomOperatorsClass
{
    公共int值{搞定;私人集; }
    公共CustomOperatorsClass(int值)
        : 这个()
    {
        值=价值;
    }    静态公共CustomOperatorsClass运营商+(
        CustomOperatorsClass一个,CustomOperatorsClass B)
    {
        返回新CustomOperatorsClass(a.value中+ b.Value);
    }
}

以下两项检查应该返回真正

  typeof运算(CustomOperatorsClass).HasOperator(Operator.Addition)
typeof运算(INT).HasOperator(Operator.Addition)


解决方案

有一个快速和肮脏的方法来找出,并同时适用于内置和自定义类型。它的主要缺点是,它依赖于在正常流量异常,但它能够完成任务。

 静态布尔HasAdd< T>(){
    变种C =前pression.Constant(默认值(T)的typeof(T));
    尝试{
        防爆pression.Add(C,C); //抛出一个异常,如果+没有定义
        返回true;
    } {抓
        返回false;
    }
}

How can I check whether a certain type implements a certain operator?

struct CustomOperatorsClass
{
    public int Value { get; private set; }


    public CustomOperatorsClass( int value )
        : this()
    {
        Value = value;
    }

    static public CustomOperatorsClass operator +(
        CustomOperatorsClass a, CustomOperatorsClass b )
    {
        return new CustomOperatorsClass( a.Value + b.Value );
    }
}

Following two checks should return true:

typeof( CustomOperatorsClass ).HasOperator( Operator.Addition )
typeof( int ).HasOperator( Operator.Addition )

解决方案

There is a quick and dirty way to find out, and it works for both built-in and custom types. Its major drawback is that it relies on exceptions in a normal flow, but it gets the job done.

 static bool HasAdd<T>() {
    var c = Expression.Constant(default(T), typeof(T));
    try {
        Expression.Add(c, c); // Throws an exception if + is not defined
        return true;
    } catch {
        return false;
    }
}

这篇关于如何验证是否型重载/支持某运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆