p; = value; }\n");
sbProperty.Append(" }");
return sbProperty.ToString();
}
propertyString方法就是用来拼写字符串的
整个代码比较简单,主要步骤就是:1、拼写类的字符串 2、调用CSharpCodeProvider类进行编译得到程序集(assembly)
接下来就可以利用之前反射的方法来动态调用这个类中的属性了:
Assembly assembly = NewAssembly();
object Class1 = assembly.CreateInstance("DynamicClass");
ReflectionSetProperty(Class1, "aaa", 10);
ReflectionGetProperty(Class1, "aaa");
object Class2 = assembly.CreateInstance("DynamicClass");
ReflectionSetProperty(Class1, "bbb", 20);
ReflectionGetProperty(Class1, "bbb");
DynamicClass是我动态类的类名,aaa和bbb是其中的属性
ReflectionSetProperty和ReflectionGetProperty代码如下:
给属性赋值
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) [Page]
{
info.SetValue(objClass, value, null);
}
}
&n