研发闲暇时间,将写代码过程中重要的代码做个珍藏,下面的代码是关于C#将字符串转换成表达式执行输出运算结果的的代码,应该对各位有用处。
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace Common.Doing
{
public class Evaluator
{
public static object Eval(string statement)
{
return _evaluatorType.InvokeMember(
"Eval",
BindingFlags.InvokeMethod,
null,
_evaluator,
new object[] { statement }
);
}
static Evaluator()
{
CodeDomProvider provider = CodeDomProvider.CreateProvider("JScript");
CompilerParameters parameters;
parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results;
results = provider.CompileAssemblyFromSource(parameters, _jscriptSource);
Assembly assembly = results.CompiledAssembly;
_evaluatorType = assembly.GetType("Evaluator");
_evaluator = Activator.CreateInstance(_evaluatorType);
}
private static object _evaluator = null;
private static Type _evaluatorType = null;
private static readonly string _jscriptSource =
@" import SharpDll;
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr);
}
public function RoundUp(numVar:double,len:int):double
var numRev:double = 0;
var dindex:int = numVar.ToString().IndexOf("+"".""+ @");
if (dindex> -1)
{
if (len == 0)
{
if (int.Parse(numVar.ToString().Substring(dindex+1))> 0)
{
numRev = double.Parse(numVar.ToString().Substring(0,dindex))+ 1;
}
}
if (len > 0)
{
if ((dindex + len) > numVar.ToString().Substring(dindex).Length)
{
numRev = numVar;
}
else
{
if (int.Parse(numVar.ToString().Substring(dindex + len+1)) > 0)
{
numRev = double.Parse(tempnum.ToString().Insert(tempnum.ToString().Length - len, " + ""."" + @"));
}
else
{
numRev = double.Parse(numVar.ToString().Substring(0, dindex + len));
}
}
}
}
else
{
numRev = numVar;
}
return numRev;
}
public function invokeInt(len:int):int
{
var TempVal:String = "+""1""+ @";
var i:int = 0;
while(i<len)
{
TempVal = TempVal+" + ""0"" + @";
i++;
}
return int.Parse(TempVal);
}
}";
}
}
调用方法
MessageBox.Show(Evaluator.Eval(exp).ToString());
网友评论