我正在尝试找出一种动态构建条件的方法。
到目前为止,这是我的代码:
var greaterThan = ">";
var a = 1;
var b = 2;
if (a Convert.ToOperator(greaterThan) b) {...}
我确实读过这篇文章,但不知道如何实现其中的一些内容:C# 转换字符串以用于逻辑条件 https://stackoverflow.com/questions/925886/c-convert-a-string-for-use-in-a-logical-condition
任何建议都将受到高度赞赏。谢谢。
我本来不想发布它,但认为它可能会有所帮助。当然,假设您不需要乔恩帖子中的高级通用逻辑。
public static class Extension
{
public static Boolean Operator(this string logic, int x, int y)
{
switch (logic)
{
case ">": return x > y;
case "<": return x < y;
case "==": return x == y;
default: throw new Exception("invalid logic");
}
}
}
您可以使用这样的代码,greaterThan
成为一个string
与想要的逻辑/运算符。
if (greaterThan.Operator(a, b))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)