0

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

这是我更改属性的代码:

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

你知道可能是什么原因吗?

谢谢

何塞。

4

1 回答 1

1

似乎您的 customerNameBldr 在 foreach 循环中从未更改(当您生成类型时)。

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

custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr); 
于 2012-10-10T10:40:54.877 回答