我试图更改与我正在循环的数据表的列名匹配的属性值(使用反射)。
这是我更改属性的代码:
Type type = myTypeBuilder.CreateType();
foreach (DataRow row in table.Rows)
{
object testobject = Activator.CreateInstance(retval, true);
foreach (DataColumn col in table.Columns)
{
PropertyInfo property = testobject .GetType().GetProperty(col.ColumnName);
property.SetValue(testobject , row[col], BindingFlags.CreateInstance, null, null, null);
}
}
结果,我在循环遍历表的 DataColumns 时获得了正确的属性,但是在 SetValue 之后,我的“testobject”的所有属性值都设置为只有所选属性应该具有的值。
这是我生成类型的方式:
foreach (DataColumn col in table.Columns)
{
string propertyname=col.ColumnName;
// The last argument of DefineProperty is null, because the
// property has no parameters. (If you don't specify null, you must
// specify an array of Type objects. For a parameterless property,
// use an array with no elements: new Type[] {})
PropertyBuilder custNamePropBldr = myTypeBuilder.DefineProperty(propertyname, System.Reflection.PropertyAttributes.None, typeof(string), null);
// The property set and property get methods require a special
// set of attributes.
MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
// Define the "get" accessor method for CustomerName.
MethodBuilder custNameGetPropMthdBldr = myTypeBuilder.DefineMethod("get_"+propertyname, getSetAttr, typeof(string), Type.EmptyTypes);
ILGenerator custNameGetIL = custNameGetPropMthdBldr.GetILGenerator();
custNameGetIL.Emit(OpCodes.Ldarg_0);
custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);
custNameGetIL.Emit(OpCodes.Ret);
// Define the "set" accessor method for CustomerName.
MethodBuilder custNameSetPropMthdBldr = myTypeBuilder.DefineMethod("set_"+propertyname, getSetAttr, null, new Type[] { typeof(string) });
ILGenerator custNameSetIL = custNameSetPropMthdBldr.GetILGenerator();
custNameSetIL.Emit(OpCodes.Ldarg_0);
custNameSetIL.Emit(OpCodes.Ldarg_1);
custNameSetIL.Emit(OpCodes.Stfld, customerNameBldr);
custNameSetIL.Emit(OpCodes.Ret);
// Last, we must map the two methods created above to our PropertyBuilder to
// their corresponding behaviors, "get" and "set" respectively.
custNamePropBldr.SetGetMethod(custNameGetPropMthdBldr);
custNamePropBldr.SetSetMethod(custNameSetPropMthdBldr);
}
你知道可能是什么原因吗?
谢谢
何塞。