动态算术运算符
我想知道是否有办法实现下一个示例:
string tmp = "+";
int ans1 = 4 tmp 5;
tmp = "+";
int ans2 = 4 tmp 5;
谢谢
I was wondering if there is a way to implement next example :
string tmp = "+";
int ans1 = 4 tmp 5;
tmp = "+";
int ans2 = 4 tmp 5;
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您至少可以这样做:
通过创建一个名为
MyOpType
的类,该类具有从string
到其自身的隐式运算符重载。这还必须运算符重载&
以返回某些缺少单个参数的运算符类型。但是,我不建议进行此类“hacks”,因为尚不清楚代码的作用。此外,我确信有更好的方法来完成您要做的事情。因此,如果您解释一下上下文,那么我们可能会找到更好的解决方案:)
我想像
Result("+", 4, 5)
这样的东西会更干净、更容易实现。这引出了我的问题:你从哪里得到操作员?用户?如果没有,肯定可以找到更好的解决方案。如果您想要某种形式的“动态解释”,那么 .Net 表达式树可能很有趣。You can do this at least:
By creating a class called
MyOpType
which have implicit operator overloading fromstring
to it self. This would also have to operator overload&
to return some operator type which miss a single argument.However, I do not recommend doing such "hacks" because it is not clear what the code does. And furthermore, I'm sure there is a better way to do what you what to do. So if you explain the context then we might find a better solution :)
I guess something like
Result("+", 4, 5)
would be cleaner and easier to implement. This leads me to the question: Where do you get the operator from? users? If not, a better solution can surely be found. If you want some form of "dynamic interpretation" then .Net Expressions trees could be interesting.确切地说,语法是 - 不。使用一些其他语法(更接近 C#) - 也许
In exact that syntax - NO. Using some other syntax (closer to C#) - maybe
这个主题被称为“表达”,有很多关于它的例子。最好的这里
祝你好运
This subject called by "expression", there are many sample about it. the best one here
Good luck