2009-07-30 79 views
4

是否有可能在c#中有动态运算符?C#动态运算符

string aString = "5"; 
int a = 5; 
int b = 6; 
string op = "<"; 

//want to do something like dynamically without checking the value of op 
if(a op b) 
+2

尝试谷歌搜索一个C#评估和演示实施,这听起来像你在找什么。 – 2009-07-30 17:10:11

+0

相关问题:http://stackoverflow.com/questions/174664/operators-as-strings – 2009-07-30 17:12:48

回答

16

您不能创建动态操作符 - 但可以将操作符包装在委托中。您可以使用lambdas来简化语法。

Func<int,int,int> opPlus = (a,b) => a + b; 
Func<int,int,int> opMinus = (a,b) => a - b; 
// etc.. 

// now you can write: 
int a = 5, b = 6; 
Func<int,int,int> op = opPlus; 
if(op(a,b) > 9) 
    DoSomething(); 

虽然不是确定的--C#的未来方向是将编译器作为服务实现。因此,在某些时候,可能会编写动态评估表达式的代码。

-1

C#4.0将为动态类型设置一个动态关键字。

1

你可能会发现像Flee有帮助。还有其他的,但他们的名字现在逃脱了我。

3

捎带上LBushkin的回应:

Func<int, int, bool> AGreaterThanB = (a,b) => a > b; 
Func<int, int, bool> ALessThanB = (a,b) => a < b; 

Func< int, int, bool> op = AGreaterThanB; 

int x = 7; 
int y = 6; 

if (op(x, y)) 
{ 
    Console.WriteLine("X is larger"); 
} 
else 
{ 
    Console.WriteLine("Y is larger"); 
} 

http://msdn.microsoft.com/en-us/library/bb549151.aspx