动态算术运算符

发布于 2024-10-15 19:20:32 字数 130 浏览 2 评论 0原文

我想知道是否有办法实现下一个示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

离线来电— 2024-10-22 19:20:32

您至少可以这样做:

MyOpType tmp = "+";
int ans1 = 4 & tmp & 5;
tmp = "+"; // Could be any operator implemented by MyOpType
int ans2 = 4 & tmp & 5;

通过创建一个名为 MyOpType 的类,该类具有从 string 到其自身的隐式运算符重载。这还必须运算符重载 & 以返回某些缺少单个参数的运算符类型。

但是,我不建议进行此类“hacks”,因为尚不清楚代码的作用。此外,我确信有更好的方法来完成您要做的事情。因此,如果您解释一下上下文,那么我们可能会找到更好的解决方案:)

我想像 Result("+", 4, 5) 这样的东西会更干净、更容易实现。这引出了我的问题:你从哪里得到操作员?用户?如果没有,肯定可以找到更好的解决方案。如果您想要某种形式的“动态解释”,那么 .Net 表达式树可能很有趣。

You can do this at least:

MyOpType tmp = "+";
int ans1 = 4 & tmp & 5;
tmp = "+"; // Could be any operator implemented by MyOpType
int ans2 = 4 & tmp & 5;

By creating a class called MyOpType which have implicit operator overloading from string 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.

不回头走下去 2024-10-22 19:20:32

确切地说,语法是 - 不。使用一些其他语法(更接近 C#) - 也许

In exact that syntax - NO. Using some other syntax (closer to C#) - maybe

無處可尋 2024-10-22 19:20:32

这个主题被称为“表达”,有很多关于它的例子。最好的这里

祝你好运

This subject called by "expression", there are many sample about it. the best one here

Good luck

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文