108 lines
3.4 KiB
C#
108 lines
3.4 KiB
C#
using System;
|
|
using System.CodeDom.Compiler;
|
|
using System.Reflection;
|
|
using System.Windows.Forms;
|
|
using CommonLib;
|
|
using System.Data;
|
|
using Microsoft.CSharp;
|
|
using System.Text;
|
|
|
|
namespace Lskj.Common {
|
|
/**/
|
|
/// <summary>
|
|
/// 动态求值
|
|
/// </summary>
|
|
public class Evaluator {
|
|
/**/
|
|
/// <summary>
|
|
/// 计算结果,如果表达式出错则抛出异常
|
|
/// </summary>
|
|
/// <param name="statement">表达式,如"1+2+3+4"</param>
|
|
/// <returns>结果</returns>
|
|
public static object Eval(string statement)
|
|
{
|
|
object obj = string.Empty;
|
|
try
|
|
{
|
|
if ((!string.IsNullOrEmpty(statement)) && (statement.Substring(0, 1) == "@"))
|
|
{
|
|
DataTable dt = SqlHelper.ExecuteDataSet(statement.Substring(1)).Tables[0];
|
|
if (dt == null)
|
|
return 0;
|
|
if (dt.Rows.Count < 1)
|
|
return 0;
|
|
return dt.Rows[0][0];
|
|
}
|
|
if (string.IsNullOrEmpty(statement))
|
|
statement = "1==1";
|
|
|
|
|
|
JSCaller caller = new JSCaller();
|
|
obj = caller.Eval(statement);
|
|
//obj = _evaluatorType.InvokeMember(
|
|
// "Eval",
|
|
// BindingFlags.InvokeMethod,
|
|
// null,
|
|
// _evaluator,
|
|
// new object[] { statement }
|
|
// );
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
//MessageBox.Show("请仔细检查配置列条件[" + statement + "]" + ex.StackTrace + "\r\n" + ex.Message);
|
|
PubUtil.WriteLog("请仔细检查配置列条件[" + statement + "]" + ex.Message);
|
|
}
|
|
//if (string.IsNullOrEmpty(obj + ""))
|
|
// return true;
|
|
return obj;
|
|
}
|
|
/**/
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
static Evaluator() {
|
|
try
|
|
{
|
|
CodeDomProvider provider = CodeDomProvider.CreateProvider("JScript");
|
|
CompilerParameters options = new CompilerParameters
|
|
{
|
|
ReferencedAssemblies = {
|
|
"System.dll",
|
|
AppDomain.CurrentDomain.BaseDirectory + @"Microsoft.JScript.dll"
|
|
},
|
|
GenerateInMemory = false
|
|
};
|
|
|
|
CompilerResults results;
|
|
results = provider.CompileAssemblyFromSource(options, _jscriptSource);
|
|
Assembly assembly = results.CompiledAssembly;
|
|
_evaluatorType = assembly.GetType("Evaluator");
|
|
_evaluator = Activator.CreateInstance(_evaluatorType);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
}
|
|
}
|
|
|
|
private static object _evaluator = null;
|
|
private static Type _evaluatorType = null;
|
|
/**/
|
|
/// <summary>
|
|
/// JScript代码
|
|
/// </summary>
|
|
private static readonly string _jscriptSource =
|
|
|
|
@"class Evaluator
|
|
{
|
|
public function Eval(expr : String) : String
|
|
{
|
|
return eval(expr);
|
|
}
|
|
}";
|
|
|
|
public static object Eval_Ex(string statement) {
|
|
return null;
|
|
}
|
|
}
|
|
}
|