更改属性值会导致所有属性发生更改

时间:2012-10-10 10:32:56

标签: c# reflection

我试图更改与我循环的数据表的列名匹配的属性值(使用反射)。

以下是我更改属性的代码:

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);
        }

你知道原因是什么吗?

由于

何。

1 个答案:

答案 0 :(得分:1)

似乎你的customerNameBldr永远不会在foreach循环中更改(当你生成类型时)。

这样所有属性设置器和getter都引用相同的字段,因此所有setter都将更改同一字段的值,所有属性getter将获得相同字段的值。

custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr);