2011-12-19 310 views
1

这是可能在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  
} 

回答

2

应该是这样的:

var props = new Dictionary<string, object>(); 
foreach(var prop in hObj.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance);) 
{ 
    props.Add(prop.Name, prop.GetValue(hObj, null)); 
} 

看到here上的GetProperties和here信息为PropertyInfo

+0

如前所述,反射会得到你想要的结果。请记住,如果您的列表变得非常大,那么Reflection效率不高,并且会导致明显的性能下降。 – 2011-12-19 22:12:54

0

您可以使用反射来获取对象的属性和值:

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)); 
} 
相关问题