Could .NET be parsed and evaluated at runtime

前端 未结 6 1505
轻奢々
轻奢々 2021-01-14 09:25

I thought it would be fun if I could write vb.net or c# code at runtime and the interpreter would automatically parse it like python does it, so I made a little program, whi

6条回答
  •  时光取名叫无心
    2021-01-14 10:22

    Don't have much time to give you a proper answer, but here is eval code from one of my old projects:

            CSharpCodeProvider c = new CSharpCodeProvider();
            ICodeCompiler icc = c.CreateCompiler();
            CompilerParameters cp = new CompilerParameters();
    
            cp.ReferencedAssemblies.Add("system.dll");
            cp.ReferencedAssemblies.Add("system.xml.dll");
            cp.ReferencedAssemblies.Add("system.data.dll");
            cp.ReferencedAssemblies.Add("system.windows.forms.dll");
            cp.ReferencedAssemblies.Add("system.drawing.dll");
    
            cp.CompilerOptions = "/t:library";
            cp.GenerateInMemory = true;
    
            StringBuilder sb = new StringBuilder("");
            sb.Append("using System;\n");
            sb.Append("using System.Xml;\n");
            sb.Append("using System.Data;\n");
            sb.Append("using System.Data.SqlClient;\n");
            sb.Append("using System.Windows.Forms;\n");
            sb.Append("using System.Drawing;\n");
    
            sb.Append("namespace CSCodeEvaler{ \n");
            sb.Append("public class CSCodeEvaler{ " + csCode + "} }");
    
            CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());
            if (cr.Errors.Count > 0)
            {
                MessageBox.Show("ERROR: " + cr.Errors[0].ErrorText,
                   "Error evaluating cs code", MessageBoxButtons.OK,
                   MessageBoxIcon.Error);
                return null;
            }
    
            System.Reflection.Assembly a = cr.CompiledAssembly;
            object o = a.CreateInstance("CSCodeEvaler.CSCodeEvaler");
    
            Type t = o.GetType();
            MethodInfo mi = t.GetMethod("Transform");
    
            return mi;
    

    Original variant of this code was taken from: http://www.codeproject.com/KB/cs/evalcscode.aspx

    It compiles some C# code (code should be in csCode variable), then tries to find Transform() method in it and returns its MethodInfo, so we can execute it.

    But remember, every time you call this code, a new assembly will be loaded, so don't use it too often.

    Also, as Prescott said - try Roslyn

    Hope this will help. Sorry that haven't provided code example more specific to your question.

    PS. If you want some interactive window, there are third party controls for this (use google to find, because I don't remember exact product names)

提交回复
热议问题