是否有可能在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)
是否有可能在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)
您不能创建动态操作符 - 但可以将操作符包装在委托中。您可以使用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#的未来方向是将编译器作为服务实现。因此,在某些时候,可能会编写动态评估表达式的代码。
C#4.0将为动态类型设置一个动态关键字。
你可能会发现像Flee有帮助。还有其他的,但他们的名字现在逃脱了我。
捎带上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");
}
尝试谷歌搜索一个C#评估和演示实施,这听起来像你在找什么。 – 2009-07-30 17:10:11
相关问题:http://stackoverflow.com/questions/174664/operators-as-strings – 2009-07-30 17:12:48