您不能使用*
運營商本身,而是可以通過生成使用此運算符的表達式解決它:
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