如何检查通用是否有运营商? C#

时间:2014-05-01 08:47:17

标签: c# generics

我想为泛型类重载operator +(f,s)。如果f和s具有加号运算符,则应返回+(f,s),否则返回null。我该怎么办?

public class param<T> : TDefault 
{
    public string param_name;
    public T cnt;
    public param(T _cnt)
    {
        cnt=_cnt;
    }
    public static param<T> operator +(param<T> f, param<T> s)
    {
        if(T ? has_operator("+"))
            return param<T>(((f.cnt as ?)+(s.cnt as ?)) as T);
        return null;
    }
}

为了检查操作员的存在,我尝试了

public static bool has_method(this object target,string method_name)
{
    return target.GetType().GetMethod(method_name)!=null;
}

但是

int x;
print (x.has_method("+="));

打印'false'

1 个答案:

答案 0 :(得分:1)

试试这个:

public class Param<T>
{
    private static readonly Func<T, T, T> addMethod;
    static Param()
    {
        try
        {
            ParameterExpression left = Expression.Parameter(typeof (T), "left");
            ParameterExpression right = Expression.Parameter(typeof (T), "right");
            addMethod = Expression.Lambda<Func<T, T, T>>(Expression.Add(left, right), left, right).Compile();
        }
        catch (InvalidOperationException)
        {
            //Eat the exception, no + operator defined :(
        }
    }

    public string param_name;
    public T cnt;
    public Param(T _cnt)
    {
        cnt = _cnt;
    }

    public static Param<T> operator +(Param<T> leftOperand, Param<T> rightOperand)
    {
        if (addMethod != null)
        {
            return new Param<T>(addMethod(leftOperand.cnt, rightOperand.cnt));
        }
        return null;
    }
}

private static void Main(string[] args)
{
    var pi = new Param<int>(5);
    var pi2 = new Param<int>(6);
    var pi3 = pi + pi2;

    var pi4 = new Param<ooject>(5);//Wont work
    var pi5 = new Param<object>(6);
    var pi6 = pi4 + pi5;
}

Credit goes to JonSkeet and Marc