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());
}发布于 2009-12-24 03:01:51
下面这样的方法怎么样:
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);发布于 2009-12-13 04:15:37
阅读错误消息。
非静态方法和属性与类的实例相关联,因此在尝试通过反射访问它们时需要提供一个实例。
发布于 2009-12-13 04:17:23
在GetProperty.GetValue方法中,您需要指定要获取其属性值的对象。在您的示例中,它将是:GetValue(CPA ,null)
https://stackoverflow.com/questions/1894550
复制相似问题