Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

reflection - How can I evaluate a C# expression dynamically?

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;
");

    sb.Append("namespace CSCodeEvaler{ 
");
    sb.Append("public class CSCodeEvaler{ 
");
    sb.Append("public object EvalCode(){
");
    sb.Append("return " + sExpression + "; 
");
    sb.Append("} 
");
    sb.Append("} 
");
    sb.Append("}
");

    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;

}  
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Old topic, but considering this is one of the first threads showing up when googling, here is an updated solution.

You can use Roslyn's new Scripting API to evaluate expressions.

If you are using NuGet, just add a dependency to Microsoft.CodeAnalysis.CSharp.Scripting. To evaluate the examples you provided, it is as simple as:

var result = CSharpScript.EvaluateAsync("1 + 3").Result;

This obviously does not make use of the scripting engine's async capabilities.

You can also specify the evaluated result type as you intended:

var now = CSharpScript.EvaluateAsync<string>("System.DateTime.Now.ToString()").Result;

To evaluate more advanced code snippets, pass parameters, provide references, namespaces and whatnot, check the wiki linked above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...