本文介绍了如何动态评估一个C#的前pression?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我愿做等价的:
对象result =的eval(1 + 3);
现在字符串=的eval(System.DateTime.Now()的ToString())作为字符串
继蔽日小号,我得到了这个片段(修改删除过时的方法 I codeCompiler.CreateCompiler()
:
私有对象与eval(String性pression)
{
CSHARP codeProvider C =新CSHARP codeProvider();
CompilerParameters CP =新CompilerParameters(); cp.ReferencedAssemblies.Add(system.dll中); cp.CompilerOptions =/ T:库;
cp.GenerateInMemory = TRUE; StringBuilder的SB =新的StringBuilder();
sb.Append(使用系统; \\ n); sb.Append(命名空间CS codeEvaler {\\ n);
sb.Append(公共类CS codeEvaler {\\ n);
sb.Append(公共对象评估和演示code(){\\ n);
sb.Append(回归+ SEX pression +\\ n);
sb.Append(} \\ n);
sb.Append(} \\ n);
sb.Append(} \\ n); CompilerResults CR = c.CompileAssemblyFromSource(CP,sb.ToString());
如果(cr.Errors.Count大于0)
{
抛出新InvalidEx pressionException(
的String.Format(错误({0})评价:{1},
cr.Errors [0] .ErrorText,性别pression));
} System.Reflection.Assembly一个= cr.CompiledAssembly;
对象o = a.CreateInstance(CS codeEvaler.CS codeEvaler); 类型t = o.GetType();
MethodInfo的MI = t.GetMethod(评估和演示code); 对象S = mi.Invoke(0,NULL);
返回S;}
解决方案
通过使用编译的飞行,喜欢的的节目。
或使用,这是完全一样的道理。
I would like to do the equivalent of:
object result = Eval("1 + 3");
string now = Eval("System.DateTime.Now().ToString()") as string
Following Biri s link, I got this snippet (modified to remove obsolete method ICodeCompiler.CreateCompiler()
:
private object Eval(string sExpression)
{
CSharpCodeProvider c = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.CompilerOptions = "/t:library";
cp.GenerateInMemory = true;
StringBuilder sb = new StringBuilder("");
sb.Append("using System;\n");
sb.Append("namespace CSCodeEvaler{ \n");
sb.Append("public class CSCodeEvaler{ \n");
sb.Append("public object EvalCode(){\n");
sb.Append("return " + sExpression + "; \n");
sb.Append("} \n");
sb.Append("} \n");
sb.Append("}\n");
CompilerResults cr = c.CompileAssemblyFromSource(cp, sb.ToString());
if (cr.Errors.Count > 0)
{
throw new InvalidExpressionException(
string.Format("Error ({0}) evaluating: {1}",
cr.Errors[0].ErrorText, sExpression));
}
System.Reflection.Assembly a = cr.CompiledAssembly;
object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
Type t = o.GetType();
MethodInfo mi = t.GetMethod("EvalCode");
object s = mi.Invoke(o, null);
return s;
}
解决方案
By using compile on the fly, like this example shows.
Or by using Flee, which is for exactly the same reason.
这篇关于如何动态评估一个C#的前pression?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!