您不能使用*
运营商本身,而是可以通过生成使用此运算符的表达式解决它:
static class Operators
{
public static T Multiply<T>(T x, T y)
{
return OperatorCache<T>.Multiply(x, y);
}
static class OperatorCache<T>
{
static OperatorCache()
{
Multiply = MakeBinaryOperator(ExpressionType.Multiply);
}
static Func<T, T, T> MakeBinaryOperator(ExpressionType type)
{
var x = Expression.Parameter(typeof(T), "x");
var y = Expression.Parameter(typeof(T), "y");
var body = Expression.MakeBinary(type, x, y);
var expr = Expression.Lambda<Func<T, T, T>>(body, x, y);
return expr.Compile();
}
public readonly static Func<T, T, T> Multiply;
}
}
然后,您可以使用它像这样:
public override T Area()
{
return Operators.Multiply(this.side, this.side);
}
当然,您可以将其他运算符添加到Operators
类中;只要记住如果您正在使用的操作员没有为T
定义,它将在运行时失败。
什么是错误? –
你见过[这篇文章](http://www.yoda.arachsys.com/csharp/genericoperators.html)吗? – Andrei
这也是有点相关:http://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c和http://social.msdn.microsoft.com/Forums/en-US/6317290d-bbfb-46f6-812b-7f4252ce3f27/operator-can-be-applied-to-operands-of-type-t-and -t – Ric