【问题标题】:dynamic if condition from string [duplicate]来自字符串的动态if条件[重复]
【发布时间】:2014-05-22 21:11:25
【问题描述】:

我正在根据一些业务规则生成一个表达式,它可能看起来像这样

0 > 1
12 < 14
"abc" != "xyz"
90 >= 12

现在我必须根据该条件进行某些实现。例如:

 string condition = "0 =1";
 if(condition)
 {
  // do something because condition is passed
 }
else
 { 
  // do something because condition is failed
 }

我已尝试对动态关键字执行相同的操作,但仍然无法正常工作。 有什么解决办法吗?

编辑:1 修改代码

string _initExp = "1";
string _validateCondition = "== 0";
string strcondition = _initExp + _validateCondition;
bool _condition = Convert.ToBoolean(strcondition); // Error statement

if (_condition)
{

}

【问题讨论】:

标签: c# if-statement dynamic


【解决方案1】:

为什么不直接使用bool

bool condition = 0==1;
if(condition)
{
   // do something because condition is passed
}
else
{ 
   // do something because condition is failed
}

您还可以简化以下代码:

bool condition = 0==1;
if(condition)
{
   return true;
}
else
{ 
   return false;
}

到:

bool condition = 0==1;
return condition;

或用于自定义返回值

bool condition = 0==1;
return condition ? "yes" : "no";

【讨论】:

  • return condition; 就足够了。为什么要再次检查。
  • 或者你甚至可以使用某种 lambda 表达式。
  • @Bharadwaj,谢谢。我无法正确表达自己。我已经更新了我的答案。希望越来越好。
  • 我以字符串格式获取我的条件 ex: "0 == 1" ,当我使用下面的代码将其转换为 bool 时它不起作用,可能是因为它无法解析这个字符串为 bool bool _condition = Convert.ToBoolean(strcondition)
  • @Zerotoinfinite,我认为这会有所帮助:stackoverflow.com/questions/5029699/…
猜你喜欢
  • 1970-01-01
  • 2012-05-09
  • 2014-04-12
  • 1970-01-01
  • 2011-02-10
  • 2015-03-14
  • 2015-04-11
  • 2018-07-07
  • 1970-01-01
相关资源
最近更新 更多