c# 将字符串转换为逻辑表达式(字符串转换布尔)


比如:string str="6>5";

要的效果是:bool result=6>5

方案1:

命名空间:System.Data;

 DataTable dt = new DataTable();

 bool result= (bool)dt.Compute("","");dt.Compute(str, "");

 

方案2:

public class Expression
{
object instance;
MethodInfo method;
/// <summary>
/// 表达试运算
/// </summary>
/// <param name="expression">表达试</param>
public Expression(string expression)
{
if (expression.IndexOf("return") < 0) expression = "return " + expression + ";";
string className = "Expression";
string methodName = "Compute";
CompilerParameters p = new CompilerParameters();
p.GenerateInMemory = true;
CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, string.
Format("using System;sealed class {0}{{public bool {1}(bool x){{{2}}}}}",
className, methodName, expression));
if (cr.Errors.Count > 0)
{
string msg = "Expression(\"" + expression + "\"): \n";
foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
throw new Exception(msg);
}
instance = cr.CompiledAssembly.CreateInstance(className);
method = instance.GetType().GetMethod(methodName);
}
/// <summary>
/// 处理数据
/// </summary>
/// <param name="x"></param>
/// <returns>返回计算值</returns>
public bool Compute(bool x)
{
return (bool)method.Invoke(instance, new object[] { x });
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM