2012-10-10 3 views
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); 
     } 

당신이 원인이 될 수있는 것을 알고 계십니까 :

내가 유형을 생성하는 방법은?

감사합니다.

호세.

+0

당신은 *에 더 정교한 수 있지만 SetValue는 후 내 "testobject"의 모든 속성 값은 선택한 속성이 가져야하는 값으로 설정됩니다. *? –

답변

1

foreach 루프에서 customerNameBldr이 절대로 변경되지 않는 것 같습니다 (유형을 생성 할 때).

이렇게하면 모든 속성 설정자와 getter가 동일한 필드를 참조하므로 모든 설정자가 동일한 필드의 값을 변경하고 모든 속성 getter는 동일한 필드의 값을 가져옵니다.

custNameGetIL.Emit(OpCodes.Ldfld, customerNameBldr); 
관련 문제