日期:2014-05-20  浏览次数:20776 次

[求助]如何将字符串表达式转换为C#的表达式?
比如有   "(50> 40   &&   50 <30)   ||   (90> 60) "   这样一个字符串,如何写一个函数,将它转换为   (50> 40   &&   50 <30)   ||   (90> 60)     ,然后判断其是否是true,false?

------解决方案--------------------
using System;
using System.Text;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;

namespace Obx.Common.Utilities
{
public class ObxEvaluator
{
object _compiled = null;
private string m_formula;

/// <summary>
/// Evaluate a numeric string
/// </summary>
public string Formula
{
get { return m_formula; }
set { m_formula = value; }
}

/// <summary>
///
/// </summary>
public ObxEvaluator() { }

/// <summary>
///
/// </summary>
/// <param name= "formula "> </param>
public ObxEvaluator(string formula)
{
Formula = formula;
}

/// <summary>
///
/// </summary>
/// <returns> </returns>
public Double Execute()
{
if (Formula == null || Formula == " ")
{
throw new Exception( "Please set formula first! ");
}
return this.Execute(Formula);
}

/// <summary>
///
/// </summary>
/// <returns> </returns>
public Boolean ExecuteBoolean()
{
if (Formula == null || Formula == " ")
{
throw new Exception( "Please set formula first! ");
}
constructEvaluator(Formula);
MethodInfo m = _compiled.GetType().GetMethod( "GetBooleanValue ");
return (Boolean)m.Invoke(_compiled, null);

}

//public DateTime ExecuteDateTime()
//{
// if (Formula == null || Formula == " ")
// {
// throw new Exception( "Please set formula first! ");
// }
// constructEvaluator(Formula);
// MethodInfo m = _compiled.GetType().GetMethod( "GetDateTimeValue ");
// return (DateTime)m.Invoke(_compiled, null);

//}

/// <summary>
///
/// </summary>
/// <param name= "formula "> </param>
/// <returns> </returns>
public Double Execute(string formula)
{
constructEvaluator(formula);
MethodInfo m = _compiled.GetType().GetMethod( "GetValue ");
return (Double)m.Invoke(_compiled, null);
}

/// <summary>
///
/// </summary>
/// <param name= "formula "> </param>
private void constructEvaluator(string formula)
{
ICodeCompiler compiler = (new CSharpCodeProvider().CreateCompiler());
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add( "system.dll ");