C#动态编译并执行字符串样例

作者:袖梨 2022-06-25

本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下

 

 代码如下复制代码

usingSystem;

usingMicrosoft.CSharp;

usingSystem.CodeDom.Compiler;

   

classProgram

{

  publicstaticvoidMain()

  {

    // The C# code to execute

    stringcode ="using System; "+

           "using System.IO; "+

           "public class MyClass{ "+

           "  public static void PrintConsole(string message){ "+

           "    Console.WriteLine(message); "+

           "  } "+

           "} ";

   

    // Compiler and CompilerParameters

    CSharpCodeProvider codeProvider =newCSharpCodeProvider();

    CompilerParameters compParameters =newCompilerParameters();

   

    // Compile the code

    CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code);

   

    // Create a new instance of the class 'MyClass'    // 有命名空间的,需要命名空间.类名

    objectmyClass = res.CompiledAssembly.CreateInstance("MyClass");

   

    // Call the method 'PrintConsole' with the parameter 'Hello World'

    // "Hello World" will be written in console

    myClass.GetType().GetMethod("PrintConsole").Invoke(myClass,newobject[] {"Hello World"});

   

    Console.Read();

  }

}

 

相关文章

精彩推荐