Is there a .NET class that represents operator types?

I would like to do the following:

*OperatorType* o = *OperatorType*.GreaterThan; int i = 50; int increment = -1; int l = 0; for(i; iol; i = i + increment) { //code } 

this concept can be blocked in javascript using eval () ... but the idea is to have a loop that can go forward or backward based on values ​​set at runtime.

Is it possible?

thanks

+7
c #
source share
5 answers

Yes, it is in .NET Expression Trees. In particular, you need to use BinaryExpression.Add () . The construction of expression trees does not need to be done manually, the compiler will be happy to convert any expressed lambda expression that it considers assigned Expression<T> to a valid expression tree.

 // Creating an expression tree. Expression<Func<int, int, bool>> greaterThan = (l, r) => l > r; int i = 50; int increment = -1; int l = 0; for(i; greaterThan(o, i); i = i + increment) { //code } 

Calling your expression tree will automatically compile it into a dynamic method, and moreThan will act effectively as a delegate.

+13
source share
 Func<int,int,bool> op = (i1, i2) => i1 > i2; 

then

 op(i, l); 
+4
source share

Edit: Added one with lambda function:

  Func<int, int, bool> lessThan = (num1, num2) => num1 < num2; Func<int, int, bool> greaterThan = (num1, num2) => num1 > num2; public void Run() { int increment = -1; int l = 0; Func<int, int, bool> c = lessThan; for (int i = 50; c(i, l); i = i + increment) { } } 

I'm sure people will come up with much more elegant solutions than this, but here it is:

  public enum Comparison { GreaterThan, LessThan } public bool Compare(int a, Comparison c, int b) { if (c == Comparison.GreaterThan) return a > b; else if (c == Comparison.LessThan) return a < b; else throw new ArgumentException(); } public void Run() { int i = 50; int increment = -1; int l = 0; Comparison c = Comparison.GreaterThan; for (i; Compare(i, c, l); i = i + increment) { } } 
+2
source share
  Func<int, int, bool> o = (x, y) => x > y; int i = 50; int increment = -1; int l = 0; for(; o(i, l) ; i = i + increment) { //code } 

or even get rid of l:

  Predicate<int> o = (x) => x > 0; int i = 50; int increment = -1; for(; o(i) ; i = i + increment) { //code } 
+1
source share

You can define your own class and implement your own operator, see http://msdn.microsoft.com/en-us/library/aa288467(VS.71).aspx

- edited
Oh, they misunderstood what you wanted, the best way for you is to use an expression or Func <> as Andrey sad.

0
source share

All Articles