首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用反射从嵌套类获取值

使用反射从嵌套类获取值
EN

Stack Overflow用户
提问于 2009-12-13 04:10:31
回答 3查看 4.8K关注 0票数 0
代码语言:javascript
复制
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());

}
EN

回答 3

Stack Overflow用户

发布于 2009-12-24 03:01:51

下面这样的方法怎么样:

代码语言:javascript
复制
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;
}

像这样使用它:

代码语言:javascript
复制
Object val = GetPropValue("Age.Value", CPA);
票数 3
EN

Stack Overflow用户

发布于 2009-12-13 04:15:37

阅读错误消息。

非静态方法和属性与类的实例相关联,因此在尝试通过反射访问它们时需要提供一个实例。

票数 1
EN

Stack Overflow用户

发布于 2009-12-13 04:17:23

GetProperty.GetValue方法中,您需要指定要获取其属性值的对象。在您的示例中,它将是:GetValue(CPA ,null)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1894550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档