使用反射在类中设置字段

时间:2014-01-16 17:17:31

标签: class reflection field

这应该很容易,但它会让我感到困惑几次。我正在尝试使用Reflection在类中设置Value。

 public class EngineeringValueClass<T> { 
      public  T Value  { get { } set { } }
 } 

然后在一个调用类中我有:

 public class MyClass { 
    EngineeringValueClass<double> Value1;
    EngineeringValueClass<double> Value2;
    // Along with many others. 
    public void SetValueByName(object FieldName,object FieldValue) {

      // Get the "Value" field of a generic EngineeringValueClass<double> 
      PropertyInfo MyValuePropRef =               
           typeof(EngineeringValueClass<double>).GetProperty("Value");
      // Get the field within this class I want to set. 
      FieldInfo MyNameFieldRef = typeof(MyClass).GetField(FieldName.ToString());

      MyValuePropRef.SetValue(MyNameFieldRef.GetValue, 
                            FieldValue, 
                            null);
   } 
}

我的目标是

SetValueByName("Value1",2.3);

使用set accessor设置Value1的“Value”。我认为我的问题是MyNameFieldRef.GetValue不返回对象引用而是返回“值”,但我不知道如何解决这个问题。我不想传递“这个”,因为那也不对。

1 个答案:

答案 0 :(得分:0)

好的,我终于明白了:

public void SetValueByName(object FieldName, object FieldValue) {
  Type t = typeof(MyClass);
  FieldInfo PrimaryField = t.GetField(FieldName.ToString());
  object ValueField = PrimaryField.GetValue(this); 
  // To get the type of Value
  MethodInfo  TypeValueField = ValueField.GetType().GetMethod("GetValueType");
  Type ValueType = (Type) TypeValueField.Invoke(ValueField, null);
  // I added a "GetValueType () { return typeof(T); } to EngineeringValueClass
  if (ValueType == typeof(Int16))
  {
       ((EngineeringValueClass<Int16>)ValueField).Value = Int16.Parse(FieldValue.ToString());
  }... 
}