【问题标题】:Setting Field Within Class using Reflection使用反射设置类内的字段
【发布时间】:2014-01-16 17:17:31
【问题描述】:

这应该很容易,但几次都让我感到困惑。我正在尝试使用反射在类中设置值。

 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 访问器设置 Value1 的“值”。我认为我的问题是 MyNameFieldRef.GetValue 不返回对象引用,而是返回“值”,但我不知道如何解决这个问题。我不想传递“这个”,因为那也不对。

【问题讨论】:

    标签: class reflection field


    【解决方案1】:

    好吧,我终于想通了:

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

    【讨论】:

      猜你喜欢
      • 2014-07-28
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      相关资源
      最近更新 更多