CSDN博客

img asciil

C#调用C#编写的脚本

发表于2008/9/28 11:42:00  337人阅读

引用 命名空间

using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

 

加入代码

private void button1_Click(object sender, EventArgs e)
        {
            ICodeCompiler vCodeCompiler = new CSharpCodeProvider().CreateCompiler();
            CompilerParameters vCompilerParameters = new CompilerParameters();

            vCompilerParameters.GenerateExecutable = false;
            vCompilerParameters.GenerateInMemory = true;

            string vSource =
                "public class Temp" +
                "{" +
                    "public double Test(double A, double B)" +
                    "{" +
                        "return A / B;" +
                    "}" +
                "}";

            CompilerResults vCompilerResults=vCodeCompiler.CompileAssemblyFromSource(vCompilerParameters, vSource);
            Assembly vAssembly = vCompilerResults.CompiledAssembly;
            object vTemp = vAssembly.CreateInstance("Temp");

            MethodInfo vTest = vTemp.GetType().GetMethod("Test");

            for (int i = 1; i < 20; i++)
            {
                object[] vParams = { 1, i };
                object vDouble = vTest.Invoke(vTemp, vParams);

                textBox1.AppendText(vDouble.ToString() + "/r/n");
            }
        }

0 0

相关博文

我的热门文章

img
取 消
img