zoukankan      html  css  js  c++  java
  • c#动态编译并执行字符串

    比较简单,步骤是这样的

    string -> compiler -> assembly -> reflection -> execution

    直接上代码:

    using System;
    using Microsoft.CSharp;
    using System.CodeDom.Compiler;
     
    class Program
    {
        public static void Main()
        {
            // The C# code to execute
            string code = "using System; " +
                          "using System.IO; " +
                          "public class MyClass{ " +
                          "   public static void PrintConsole(string message){ " +
                          "       Console.WriteLine(message); " +
                          "   } " +
                          "} ";
     
            // Compiler and CompilerParameters
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CompilerParameters compParameters = new CompilerParameters();
     
            // Compile the code
            CompilerResults res = codeProvider.CompileAssemblyFromSource(compParameters, code);
     
            // Create a new instance of the class 'MyClass'

        // 有命名空间的,需要命名空间.类名 object myClass = 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, new object[] {"Hello World" }); Console.Read(); } }

      

  • 相关阅读:
    课程作业(一)
    PTA 5-3 解题报告
    作业(四)
    C#循环语句整理
    C#数组和集合整理
    作业(三)
    1.0总结
    如何在C++中产生随机数
    CLSRSC-400: A system reboot is required to continue installing.
    Upgrade a Non-CDB To a PDB on CDB
  • 原文地址:https://www.cnblogs.com/y114113/p/6306994.html
Copyright © 2011-2022 走看看