将对象属性映射到使用C的数组#
问题描述:
这是可能在C#
中做的吗?将对象属性映射到使用C的数组#
我有POCO对象这里是定义:
public class Human
{
public string Name{get;set;}
public int Age{get;set;}
public int Weight{get;set;}
}
我想对象Human
的属性映射到字符串数组。
事情是这样的:
Human hObj = new Human{Name="Xi",Age=16,Weight=50};
或者,我可以有List<Human>
:
string [] props = new string [COUNT OF hObj PROPERTIES];
foreach(var prop in hObj PROPERTIES)
{
props["NAME OF PROPERTIES"] = hObj PROPERTIES VALUE
}
答
您可以使用反射来获取对象的属性和值:
var properties = typeof(Human).GetProperties();
IList<KeyValuePair<string, object>> propertyValues = new List<KeyValuePair<string, object>>();
foreach (var propertyInfo in properties)
{
propertyValues.Add(propertyInfo.Name, propertyInfo.GetValue(oneHuman));
}
如前所述,反射会得到你想要的结果。请记住,如果您的列表变得非常大,那么Reflection效率不高,并且会导致明显的性能下降。 – 2011-12-19 22:12:54