【发布时间】:2014-10-16 10:40:06
【问题描述】:
我认为我的代码对于我想要实现的目标是不言自明的:
private bool Comparison<T>(T operatorOne, T operatorTwo, string operand)
{
switch (operand.ToLower())
{
case "=":
return operatorOne.Equals(operatorTwo);
case "<":
return operatorOne < operatorTwo;
case ">":
return operatorOne > operatorTwo;
case "contains":
return operatorOne.ToString().Contains(operatorTwo.ToString());
default:
return false;
}
}
它给了我错误:
Error 16 Operator '>','<' cannot be applied to operands of type 'T' and 'T'
我需要一个可以比较字符串、Int、Double、chars 的方法。 注意:排除字符串将被传递为>或
【问题讨论】:
-
您将“运算符”和“操作数”的概念倒过来。在表达式
a + b中,a和b是操作数,+是运算符。 -
是的,对不起!我的错:)
-
你对T有什么了解,如果你规定
where T : IComparable,你可能就可以逍遥法外了。 -
@mrtig T 在我的情况下只能是 int、double、float、decimal、string、char
标签: c# generics comparison operators operands