美文网首页
C# 动态执行代码

C# 动态执行代码

作者: 老中医167788 | 来源:发表于2021-12-15 17:12 被阅读0次
    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\n" +
    
           "{\n" +
    
           "  public double Test(double A, double B)\n" +
    
           "  {\n" +
    
           "      return A / B;\n" +
    
           "  }\n" +
    
           "}\n";
    
       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 < 100; i++)
    
       {
    
           object[] vParams = { 1, i };
    
           object vDouble = vTest.Invoke(vTemp, vParams);
    
           textBox1.AppendText(vDouble.ToString() + "\r\n");
    
       }
    
    }
    

    相关文章

      网友评论

          本文标题:C# 动态执行代码

          本文链接:https://www.haomeiwen.com/subject/khepfrtx.html