是否有可能在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