日期:2014-05-18 浏览次数:20928 次
class Class2 { public Class2() { Console.WriteLine("class2"); } }
static void Main(string[] args) { CSharpCodeProvider codeProvide = new CSharpCodeProvider(); ICodeCompiler codeCompiler = codeProvide.CreateCompiler(); CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.Core.dll"); compilerParameters.GenerateExecutable = false; compilerParameters.GenerateInMemory = true; CompilerResults cr = codeCompiler.CompileAssemblyFromSource(compilerParameters, GenerateCode()); if (cr.Errors.HasErrors) { Console.WriteLine("编译错误:"); foreach (CompilerError err in cr.Errors) { Console.WriteLine(err.ErrorText); } } else { Assembly assembly = cr.CompiledAssembly; object helloword = assembly.CreateInstance("PINQ_test_ConsoleApplication.HelloWorld"); MethodInfo methodInfo = helloword.GetType().GetMethod("OutPut"); object[] objs = new object[1]; objs[0] = "fuckYou"; char[] cc = (char[])methodInfo.Invoke(helloword, objs); Console.WriteLine(cc[0].ToString()); Console.WriteLine(new String(cc)); } Console.ReadLine(); } static string GenerateCode() { StringBuilder sb = new StringBuilder(); sb.Append("using System;using System.Linq;"); sb.Append(Environment.NewLine); sb.Append("namespace PINQ_test_ConsoleApplication"); sb.Append(Environment.NewLine); sb.Append("{"); sb.Append(Environment.NewLine); sb.Append(" public class HelloWorld"); sb.Append(Environment.NewLine); sb.Append(" {"); sb.Append(Environment.NewLine); sb.Append(" public char[] OutPut(string str)"); sb.Append(Environment.NewLine); sb.Append(" {"); sb.Append(Environment.NewLine); [color=#FF0000] sb.Append("Class2 cc=new Class2(); return str.ToArray();");[/color] 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); //Console.WriteLine(); return code; }