2014-01-16 40 views
1

這應該很容易,但它可以讓我困惑幾次。我正在嘗試使用Reflection在類中設置一個值。使用反射在課堂上設置字段

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

然後在調用I類有:

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

設置值1的 「值」 使用set訪問。我認爲我的問題是,MyNameFieldRef.GetValue不返回對象引用,而是一個「價值」,但我不知道如何解決這個問題。我不想通過「這個」,因爲那也不對。

回答

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