【发布时间】:2014-06-17 17:59:30
【问题描述】:
我想为泛型类重载运算符 +(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("+="));
打印“假”
【问题讨论】:
-
你知道运算符重载方法应该存在于同一个类中吗?
param<T>可以重载param<T>的运算符而不是T的运算符。 -
我的错误。我正在修复它。
-
修正了参数的代码
-
int x; print (x.has_method("op_Addition"));也打印 False