using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class Program
{
public static string PrintStr()
{
StringBuilder sb = new StringBuilder();
sb.Append("using System;");
sb.Append(Environment.NewLine);
sb.Append("namespace PrintString{");
sb.Append(Environment.NewLine);
sb.Append("public class Print{");
sb.Append(Environment.NewLine);
sb.Append("public static string ReturnTxt(String txt){");
sb.Append(Environment.NewLine);
sb.Append("if(txt == \"123\"){return \"PASS\";} else{return \"NG\";}");
sb.Append(Environment.NewLine);
sb.Append("}");
sb.Append(Environment.NewLine);
sb.Append("}");
sb.Append(Environment.NewLine);
sb.Append("}");
string code = sb.ToString();
Console.WriteLine(code);
return code;
}
static void Main(string[] args)
{
CSharpCodeProvider CodeProvider = new CSharpCodeProvider();
CompilerParameters Parameters = new CompilerParameters();
Parameters.GenerateInMemory = true;
CompilerResults Results = CodeProvider.CompileAssemblyFromSource(Parameters, PrintStr());
if (Results.Errors.HasErrors)
{
Console.WriteLine("编译失败");
}
Assembly HelloWorldAssembly = Results.CompiledAssembly;
Type type = HelloWorldAssembly.GetType("PrintString.Print");
Object theObj = Activator.CreateInstance(type);
Type[] structure_Type = new Type[1];
//定义构造函数传参类型
Object[] structure_Obj = new Object[1];
structure_Type[0] = Type.GetType("System.String");
structure_Obj[0] = "kkk";
//此处调用方法,如果有参数只需要在括号的后面加上"," 加上参数的type[]类型的参数
MethodInfo mi = type.GetMethod(string.Format("{0}", "ReturnTxt"), structure_Type);
Object returnValue = mi.Invoke(theObj, structure_Obj);
string result = returnValue.ToString();
Console.WriteLine("result is {0}",result);
}
}
}
C# 如何动态编译、执行代码
最新推荐文章于 2024-03-26 19:24:46 发布