C#动态算子

C#动态算子,c#,dynamic,C#,Dynamic,是否可以在c#中使用动态运算符 string aString=“5”; INTA=5; int b=6; string op=“C#4.0将有一个用于动态键入的动态关键字。您不能创建动态运算符,但可以在委托中包装运算符。您可以使用lambdas简化语法 Func<int,int,int> opPlus = (a,b) => a + b; Func<int,int,int> opMinus = (a,b) => a - b; // etc.. // now y

是否可以在c#中使用动态运算符

string aString=“5”;
INTA=5;
int b=6;

string op=“C#4.0将有一个用于动态键入的动态关键字。

您不能创建动态运算符,但可以在委托中包装运算符。您可以使用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();
Func opPlus=(a,b)=>a+b;
Func op减号=(a,b)=>a-b;
//等等。。
//现在你可以写:
INTA=5,b=6;
Func op=opPlus;
如果(op(a,b)>9)
DoSomething();

虽然还不确定——C的未来方向是将编译器作为一种服务来实现。因此,在某种程度上,编写动态计算表达式的代码是可能的。

您可能会发现一些有用的东西。还有其他的,但我现在不知道它们的名称。

基于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" );
}
Func agreaterhanb=(a,b)=>a>b;
Func-alesthanb=(a,b)=>aop=agreaterhanb;
int x=7;
int y=6;
if(op(x,y))
{
Console.WriteLine(“X更大”);
}
其他的
{
Console.WriteLine(“Y较大”);
}

你为什么想要一个动态操作符?也许你应该尝试使用泛型或downcast来主要与动态框架和语言进行objectInteroperation。无论如何,这对他没有帮助,因为它不做
eval
——这正是他真正想要的。我知道动态关键字应该做什么:用谷歌搜索C#eval impleme这听起来像是你要找的。相关问题:
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" );
}