[C#]调用字符串中定义的函数

http://blogs.msdn.com/b/digitalnetbizz/archive/2004/01/31/create-assembly-in-memory-and-run-it.aspx

using System;
using Specialized = System.Collections.Specialized;
using Reflection = System.Reflection;
using CSharp = Microsoft.CSharp;
using CodeDom = System.CodeDom.Compiler;
using System.Linq;
using System.Text;

namespace CSScript
{
    class CSScriptTest
    {
        //static string ScriptCodeToCompileInMem = "public class Script {public void ScriptExecute(){System.Console.WriteLine(123);} }";
        static string ScriptCodeToCompileInMem = "public class Script {public void ScriptExecute(string x){System.Console.WriteLine(x);} }";
        static void Main(string[] args)
        {
            CSScriptTest tc = new CSScriptTest();
            tc.Execute(CSScriptTest.ScriptCodeToCompileInMem);
            Console.WriteLine("---");
            Console.ReadLine();
        }

        public void Execute(string scriptCode)
        {
            string[] source = new string[1];
            source[0] = scriptCode;
            this.Compile(source[0]);
        }

        private void Compile(string source)
        {
            CodeDom.CompilerParameters param = new CodeDom.CompilerParameters();
            param.GenerateExecutable = false;
            param.IncludeDebugInformation = false;
            param.GenerateInMemory = true;
            CodeDom.CodeDomProvider cc = CodeDom.CodeDomProvider.CreateProvider("CSharp");
            CodeDom.CompilerResults cr = cc.CompileAssemblyFromSource(param, source);
            Specialized.StringCollection output = cr.Output;
            if (cr.Errors.Count != 0)
            {
                System.Console.WriteLine("Error invoking scripts.");
                CodeDom.CompilerErrorCollection es = cr.Errors;
                foreach (CodeDom.CompilerError s in es) System.Console.WriteLine(s.ErrorText);
            }
            else
            {
                object o = cr.CompiledAssembly.CreateInstance("Script");
                System.Type type = o.GetType();
                //type.InvokeMember("ScriptExecute",
                //    Reflection.BindingFlags.InvokeMethod | Reflection.BindingFlags.Default,
                //    null, o, null);
                type.InvokeMember("ScriptExecute",
                    Reflection.BindingFlags.InvokeMethod | Reflection.BindingFlags.Default,
                    null, o, new object[] { "123" });
            }
        }

    }
}



你可能感兴趣的:([C#]调用字符串中定义的函数)