需要引入命名空间 using System.CodeDom; using System.CodeDom.Compiler; using Microsoft.CSharp; using System.Reflection; public static Assembly NewAssembly() { CSharpCodeProvider provider = new CSharpCodeProvider(); CompilerParameters param = new CompilerParameters(); param.GenerateExecutable = false; param.GenerateInMemory = true; StringBuilder classSource = new StringBuilder(); classSource.Append("public class DynamicClass "); classSource.Append(" { "); classSource.Append(propertyString("aaa")); classSource.Append(" "); classSource.Append(propertyString("bbb")); classSource.Append(" "); classSource.Append(propertyString("ccc")); classSource.Append(" "); classSource.Append(" }"); CompilerResults result = provider.CompileAssemblyFromSource(param, classSource.ToString()); Assembly assembly = result.CompiledAssembly; return assembly; } private static string propertyString(string propertyName) { StringBuilder sbProperty = new StringBuilder(); sbProperty.Append(" private int _" + propertyName + " = 0; "); sbProperty.Append(" public int " + propertyName + " "); sbProperty.Append(" { "); sbProperty.Append(" get{ return _" + propertyName + ";} "); sbProperty.Append(" set{ _" + propertyName + " = value; } "); sbProperty.Append(" }"); return sbProperty.ToString(); } private static void ReflectionSetProperty(object objClass, string propertyName, int value) { PropertyInfo[] infos = objClass.GetType().GetProperties(); foreach (PropertyInfo info in infos) { if (info.Name == propertyName && info.CanWrite) { info.SetValue(objClass, value, null); } } } private static void ReflectionGetProperty(object objClass, string propertyName) { PropertyInfo[] infos = objClass.GetType().GetProperties(); foreach (PropertyInfo info in infos) { if (info.Name == propertyName && info.CanRead) { System.Console.WriteLine(info.GetValue(objClass, null)); } } } //调用 object myClass = NewAssembly().CreateInstance("DynamicClass"); ; ReflectionSetProperty(myClass, "ccc", 123465); ReflectionGetProperty(myClass, "ccc");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)