C#动态运算符 [英] C# dynamic operator

查看:156
本文介绍了C#动态运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在c#中有一个动态运算符吗?

Is it possible to have a dynamic operator in 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来简化语法。

You can't create dynamic operators - but you can wrap an operator in a delegate. You can use lambdas to simplify the syntax.

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#的未来发展方向是将编译器实现为服务。因此,在某些时候,可能会编写动态评估表达式的代码。

Although it's not definite - the future direction for C# is to implement the compiler as a service. So, at some point, it may be possible to write code that dynamically evaluates an expression.

这篇关于C#动态运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆