isu*_*mit 0 c# generics comparison operators operands
我认为我的代码可以自我解释我想要实现的目标:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
它给了我错误:
Error 16 Operator '>','<' cannot be applied to operands of type 'T' and 'T'
Run Code Online (Sandbox Code Playgroud)
我需要一个可以比较字符串,Int,Double,chars的方法.注意:排除将为>或<check>传递字符串的条件或将为"包含"检查发送Int
你可以Comparer<T>.Default.Compare(operatorOne, operatorTwo)用来比较.请注意,如果T没有实现IComparable和IComparable<T>,Comparer<T>.Default.Compare抛出异常.
要确保T实现IComparable,您可以添加where T: IComparable约束.(它将排除实现的类IComparable<T>,但不包括 IComparable.仍然可以接受,因为许多类实现IComparable<T>,也实现IComparable.)
private bool Comparison<T>(T operatorOne, T operatorTwo, string operand)
where T: IComparable
{
switch(operand.ToLower())
{
case "=":
return Comparer<T>.Default.Compare(operatorOne, operatorTwo) == 0;
case "<":
return Comparer<T>.Default.Compare(operatorOne, operatorTwo) < 0;
case ">":
return Comparer<T>.Default.Compare(operatorOne, operatorTwo) > 0;
case "contains":
return operatorOne.ToString().Contains(operatorTwo.ToString());
default:
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
PS
正如Servy建议的那样,您也可以IComparer作为额外参数传递给函数.它将允许涵盖既不实现IComparable也不实现的类型IComparable<T>,因此Comparer<T>.Default不适用于它们.
此外,信用去@TimothyShields,谁建议Comparer<T>.Default.
| 归档时间: |
|
| 查看次数: |
884 次 |
| 最近记录: |