获取对象属性的名称和值 [英] Get the name and value of an attribute of an object

查看:311
本文介绍了获取对象属性的名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法返回包含对象的所有公共属性的字典。我可以得到属性的名称(类变量)但我不能得到相同的值。谁能告诉我如何通过以下方法实现这一点:



I have the following method to return a dictionary with all public attributes of an object. I can get the name of the attributes (class variables) but I can not get the values ​​of the same. Could anyone tell me how to achieve this in the method below:

public Dictionary<String, String> ObjectProperty(object objeto)
 {
    Dictionary<String, String> dictionary = new Dictionary<String, String>();

    Type type = objeto.GetType();
    FieldInfo[] field = type.GetFields();
    PropertyInfo[] myPropertyInfo = type.GetProperties();

    String value = null;

    foreach (var propertyInfo in myPropertyInfo)
    {
        value = (string) propertyInfo.GetValue(this, null); //Here is the error
        dictionary.Add(propertyInfo.Name.ToString(), value);

    }

    return dictionary;

}

推荐答案

在您标记的行中使用此项:

Use this in the row you have marked:
value = propertyInfo.GetValue(objeto).ToString(); 



但你必须知道,这是一种非常简化的方法。由于属性可能比标量值更复杂,如果您想使方法更通用,则必须添加更多逻辑。


But you have to know, that this is a really simplified approach. Since properties can be more complex than scalar values if you want to make your method more general, you will have to add more logic.


这篇关于获取对象属性的名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆