这些值来自于 xml
文件,用户只需要声明要执行的条件。
string condition ="25<10";
现在,我想在if条件语句中使用它,例如:
if(condition)
{
//my condition
}
我遇到了这个错误
Cannot implicitly convert type string to bool
有人能告诉我如何做到这一点吗?
DataTable
:
https://msdn.microsoft.com/zh-cn/library/system.data.datatable.compute(v=vs.110).aspx
private static bool ComputeCondition(string value) {
using (DataTable dt = new DataTable()) {
return (bool)(dt.Compute(value, null));
}
}
...
string condition ="25<10";
if (ComputeCondition(condition)) {
//my condition
}
<>
代替!=
。 - Dmitry Bychenkostring condition ="25<10"
condition的值将会是25<10而不是true或false!如果25,10和<号来自于你的xml,请把它们分别放入三个不同的字符串比如x、y和z,并像下面这样进行比较:
string input = "25<10"; //input form your xml
int operatorPosition;
//get the position of the operator
if(input.contains("<")){
operatorPosition = input.IndexOf("<");
}else{
operatorPosition = input.IndexOf(">");
}
//maybe i messed up some -1 or +1 here but this should work this
string x = input.Substring(0,operatorPosition-1);
string y = input.Substring(operatorPosition+1, input.length-1);
string z = input.charAt(operatorPosition);
//check if it is < or >
if(z.equals("<"){
//compare x and y with <
if(Int32.parse(x) < Int32.parse(y)){
//do something
}else{
//do something
}
}
//z does not equal < so it have to be > (if you dont have something like = otherwise you need to check this too)
else{
if(Int32.parse(x) < Int32.parse(y)){
//do something
}else{
//do something
}
x = "25 < 10"
。这需要使用 Contains
方法来确定小于运算符和 String.Split
来获取两个操作数,然后可以在 if 条件语句中进行比较。 - Tetsuya Yamamotostring statment = "10<25"; // Sample statement
string leftOperand = statment.Split('<').First();
string rightOperand = statment.Split('<').Last();
int relationValue = Math.Sign(leftOperand.CompareTo(rightOperand));
if(relationValue == -1)
{
// leftOperand < rightOperand
}
else if (relationValue == 0)
{
// leftOperand == rightOperand
}
else if (relationValue == 1)
{
// leftOperand > rightOperand
}
如果您只想检查leftOperand < rightOperand
,您可以使用三元运算符
,如下所示:
bool condition = Math.Sign(leftOperand.CompareTo(rightOperand)) == -1 ? true : false;
condition ? first_expression : second_expression;
,但它仍然是一个 if 条件语句的简短版本。 - T. JungleftOperand < rightOperand
)吗? - Ali SoltanileftOperand < rightOperand
,而不需要使用if
。请看这个。 - Ali Soltani
if (25 < 10)
是有效的,但if ("25 < 10")
是无效的)。 - Tetsuya Yamamoto