2011-12-19 280 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)); 
} 
相關問題