using System; using System.CodeDom.Compiler; using Microsoft.CSharp; using System.Reflection; using System.Configuration; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //在App.Config中读取类的定义字符串 string ClassDefined = ConfigurationManager.AppSettings["ClassDefined"]; //创建代码编译器 CSharpCodeProvider codeProvider = new CSharpCodeProvider(); //设置编译参数 CompilerParameters paras = new CompilerParameters(); //设置在内存中生成输出。 paras.GenerateInMemory = true; //编译代码 CompilerResults result = codeProvider.CompileAssemblyFromSource(paras, ClassDefined); //获取编译后的程序集 Assembly assembly = result.CompiledAssembly; //获取反射出来的对象 Object dynamicClass = assembly.CreateInstance("CSharp.Dynamic.Employee"); //获取员工实例的类型 Type employee = dynamicClass.GetType(); //设置属性 employee.GetProperty("ID").SetValue(dynamicClass, 1, null); employee.GetProperty("Name").SetValue(dynamicClass, "李林峰", null); employee.GetProperty("Department").SetValue(dynamicClass, "技术部", null); employee.GetProperty("Position").SetValue(dynamicClass, "程序员", null); //读取属性 string Name = employee.GetProperty("Name").GetValue(dynamicClass, null).ToString(); string Department = employee.GetProperty("Department").GetValue(dynamicClass, null).ToString(); string Position = employee.GetProperty("Position").GetValue(dynamicClass, null).ToString(); //执行方法 string ParmAndID = employee.GetMethod("Method").Invoke(dynamicClass, new object[] { "员工编号:" }).ToString(); //输出 Console.WriteLine(Name); Console.WriteLine(Department); Console.WriteLine(Position); Console.WriteLine(ParmAndID); Console.Read(); } } }
<?xml version="1.0"?> <configuration> <appSettings> <add key="ClassDefined" value="namespace CSharp.Dynamic{ public class Employee{ public int ID { get; set; } public string Name { get; set; } public string Department { get; set; } public string Position { get; set; } public string Method(string parm){return parm+this.ID.ToString();} }}"/> </appSettings> <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>