获取对象属性的名称和值
问题描述:
我有以下方法返回包含对象的所有公共属性的字典。我可以得到属性的名称(类变量)但我不能得到相同的值。谁能告诉我如何通过以下方法实现这一点:
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.