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)
ダイナミック演算子を作成することはできませんが、演算子をデリゲートにラップすることはできます。ラムダを使用して構文を単純化することができます。
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には、動的型付けのための動的なキーワードを持つことになります。
v2 atmに限定 –
なぜ動的演算子が必要ですか?おそらく、ジェネリックまたはオブジェクトをダウンキャストしてみるべきです。 –
主に動的なフレームワークと言語との相互運用。 – Dykam
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#エバール実装のためにグーグルで試してみてください。 –
関連の質問:http://stackoverflow.com/questions/174664/operators-as-strings –