public class CustomProperty<T>
{
private T _value;
public CustomProperty(T val)
{
_value = val;
}
public T Value
{
get { return this._value; }
set { this._value = value; }
}
}
public class CustomPropertyAccess
{
public CustomProperty<string> Name = new CustomProperty<string>("cfgf");
public CustomProperty<int> Age = new CustomProperty<int>(0);
public CustomPropertyAccess() { }
}
//I jest beginer in reflection.
//How can access GetValue of CPA.Age.Value using fuly reflection
private void button1_Click(object sender, EventArgs e)
{
CustomPropertyAccess CPA = new CustomPropertyAccess();
CPA.Name.Value = "lino";
CPA.Age.Value = 25;
//I did like this . this is the error 「 Non-static method requires a target.」
MessageBox.Show(CPA.GetType().GetField("Name").FieldType.GetProperty("Value").GetValue(null ,null).ToString());
}
0
A
回答
1
閱讀錯誤消息。
非靜態方法和屬性與一個類的實例相關聯 - 所以當你試圖通過反射訪問它們時你需要提供一個實例。
0
在GetProperty.GetValue
方法中,您需要指定要獲取其屬性值的對象。對你來說,這將是:GetValue(CPA ,null)
2
怎麼樣這樣的方法:
public Object GetPropValue(String name, Object obj) {
foreach (String part in name.Split('.')) {
if (obj == null) { return null; }
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(part);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
}
return obj;
}
並使用它像這樣:
Object val = GetPropValue("Age.Value", CPA);
相關問題
- 1. 使用反射從嵌套類獲取值
- 2. 獲取嵌套的對象屬性值使用反射
- 3. Java反射 - 獲取嵌套類中字段的值
- 4. 通過雙重嵌套類的反射獲取值
- 5. 使用反射用typeof嵌套類型
- 6. 通嵌套類使用反射
- 7. 使用反射獲取類變量值
- 8. 使用反射來獲得一個嵌套的屬性值
- 9. 支持獲取嵌套對象字段值的java反射庫。
- 10. 通過反射獲取嵌套的屬性值C#
- 11. 使用反射從類的列表中獲取屬性值
- 12. C#使用IDictionary嵌套反射SetValue
- 13. 使用反射來獲取靜態類
- 14. 使用反射來獲取類描述
- 15. 使用反射獲取類型
- 16. 使用反射獲取類方法
- 17. 獲取容器類型使用反射
- 18. 使用Java反射類獲取方法
- 19. 使用反射獲取MemberInfo的類型
- 20. 在嵌套類中的反射
- 21. Java:靜態嵌套類和反射:「$」vs「。」
- 22. C#反射PropertyInfo MVC中的嵌套類
- 23. C#使用反射獲取parms的值
- 24. 使用反射獲取屬性的值
- 25. 使用反射獲取字段值
- 26. 嵌套屬性值反射的LINQ
- 27. 階反射獲取類enumaration價值
- 28. Java:在嵌套參數化類型中獲取內部類型(反射)
- 29. 獲取從數組父/子映射嵌套陣列陣列值
- 30. 從反射獲取實際類型fieldInfo