值来自xml
,用户只声明要执行的条件。
string condition ="25<10";
现在,我想在if条件中使用它:
if(condition)
{
//my condition
}
我收到此错误
Cannot implicitly convert type string to bool
谁能告诉我怎么做?
答案 0 :(得分:5)
如果提供的条件不是复杂,您可以尝试使用DataTable
的旧技巧:
https://msdn.microsoft.com/en-us/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
}
答案 1 :(得分:0)
首先:
如果您执行此操作string condition ="25<10"
条件将具有 25 <10 的值,而不是true或flase!如果25,10和&lt;来自你的xml将它们粘贴到3个不同的字符串中,如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
}
也许有更好的方法将纯字符串输入转换为if子句,但这就是我要去的方式。
答案 2 :(得分:0)
您可以使用此代码执行此操作:
string 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
,可以使用ternary operator
,如下所示:
bool condition = Math.Sign(leftOperand.CompareTo(rightOperand)) == -1 ? true : false;