【问题标题】:How to convert a condition string to a boolean format?如何将条件字符串转换为布尔格式?
【发布时间】:2021-07-01 01:21:17
【问题描述】:

我自学了 C#。我坚持以下。如何将条件字符串转换为布尔格式?

string ConditionString = "1 > 2";
bool Judgment = Convert.ToBoolean(ConditionString); //Error
textBox1.Text = Convert.ToString(Judgment);

【问题讨论】:

  • 你需要在你的应用程序中运行一个完整的编译器

标签: c# string type-conversion boolean conditional-statements


【解决方案1】:

您可以使用此代码块(在System.Data 命名空间中):

DataTable dt = new DataTable();
bool judgment = Convert.ToBoolean(dt.Compute("1 > 2", null));

结果为@​​987654323@ 或false

【讨论】:

  • 谢谢!您的代码运行良好。但是,诸如“3>2 && 2>1”或“apple”=="banana" 之类的条件字符串会导致错误。你能有机会解决这个问题吗..?再次感谢!
  • @JustTemp 那里的代码不是 C#,你需要用不同的方式写东西。您的示例是“3>2 and 2>1”和“'apple'='banana'”。
  • @JustTemp 欢迎您。正如@Theraot 所说,你应该使用你的条件短语作为And,Or,(等)。在您的情况下:例如"3>2 And 2>1"。如果您的输入不是这种格式,最好的方法是使用String.Replace 方法来更改它。
  • 非常感谢大家!问题似乎已经解决了!祝你有美好的一天:)
猜你喜欢
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 2021-09-22
  • 2011-02-17
  • 2012-04-02
  • 2021-02-23
  • 2010-10-15
相关资源
最近更新 更多