简体   繁体   English

C#中的比较运算符

[英]Comparison Operator in C#

I have a vague requirement. 我有一个模糊的要求。 I need to compare two values. 我需要比较两个值。 The values may be a number or a string. 值可以是数字或字符串。

I want to perform these operations >, <, ==,<>, >=,<= 我要执行这些操作>,<,==,<>,> =,<=

In my method I will pass, the parameter1, parameter 2 and the operators of above. 在我的方法中,我将传递参数1,参数2和上面的运算符。

How can compare the two values based on the operator as effectively in .NET 2.0. 如何在.NET 2.0中有效地基于运算符比较两个值。

My method should be as simplified for both String and integer input values. 对于字符串和整数输入值,我的方法都应该简化。

Sample Input Value: 样本输入值:

param1  |  param2  |  operator
------------------------------
David      Michael       >
1          3             ==

Provided both parameters are always of the same type you could use a generic method where both parameters implement IComparable<T> (introduced in .NET 2.0) 如果两个参数始终具有相同的类型,则可以使用通用方法,其中两个参数都实现IComparable<T> (在.NET 2.0中引入)

public int CompareItems<T>(T item1, T item2) where T: IComparable<T>
{
    return item1.CompareTo(item2);
}

(You can interpret the result of CompareTo() depending on the operator your pass in your implementation) (您可以根据实现过程中通过的运算符来解释CompareTo()的结果)

If you have to/want to build generic version you need to pass comparison as function/lambda - it is not possible to use operators in generic way. 如果必须/想要构建通用版本,则需要通过比较作为函数/ ​​lambda-无法以通用方式使用运算符。 Somithing like: 像这样:

class OpComparer<T>
{
  Func<T,T,bool> operation;
  public OpComparer(Func<T,T,bool> op)
  {
    operation = op;
  }

  int PerformOp(T item1, T item2) 
  {
    return operation(item1, item2);
  }
}

...
var comparerLess = new OpCompared<String>((a,b)=> a < b );
var result = comparerLess.PerformOp("aaa", "bbb");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM