2014-03-24 32 views
2

我正在尋找解決方案來解決此問題。迭代對象列表並獲取帶有字符串的元素屬性

我得到了一個對象:

- Person (String ID, String FirstName, String LastName) 

我有一個列表與一對夫婦Persons

- List<Person> persons; 

什麼我的目標是:

1. Iterate through List 
2. Get property value from that element with a string named to that property 

例如:

我想知道 人在列表中的ID:

我可以這樣做:

foreach(Person p in persons) 
{ 
    String personId = p.ID; 
} 

但我想要做這樣的事情:

foreach(Person p in persons) 
{ 
    String personId = p. + "ID"; 
} 

我要追加字符串"ID"得到該元素的ID,而不是調用p.ID

這可能嗎?我需要一個解決方案,我花了很多時間,但在互聯網上找不到任何解決方案。

+2

你爲什麼要這麼做? – khellang

+1

你應該使用反射,看看這個[問題](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp)。 –

+0

@khellang我正在閱讀帶有ID和屬性名稱的文本文件。我通過他們的ID(從文件中讀取)獲取這些人並將其放入一個列表中。然後我從該文件中讀取屬性名稱(字符串)並遍歷我填充的列表,並通過文件中的讀取字符串獲取元素的屬性值。 – Swag

回答

5

你可以使用反射來按名稱獲取屬性的值:

foreach (Person p in persons) 
{ 
    var personId = typeof(Person).GetProperty("ID").GetValue(p, null) as string; 
} 

當然,這需要一些錯誤處理和一些null檢查,但你的要點:)

+1

該死的你快。這是一個很好的解決方案! – niklon

+0

感謝您的回答。所以通過字符串獲取屬性值在c#中被稱爲Reflection? – Swag

+0

@ y451n是的。你可以閱讀'Type.GetProperty' [here](http://msdn.microsoft.com/en-us/library/kz0a8sxy.aspx)。 – khellang

1

如前所述通過其他答案,最簡單的方法(儘管也許不是最好的方法)是使用反射。

我已經包括在下面的類爲基本數據類型的支持和字符串(和加入另外的屬性來演示如何可以用於基本數據類型):

public class Person { 
    public string ID { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public int Age { get; set; } 

    private PropertyInfo GetProperty(string name) { 
     PropertyInfo property = GetType().GetProperty(name); 

     if (property == null) { 
      throw new ArgumentException(string.Format("Class {0} doesn't expose a {1} property", GetType().Name, name)); 
     } 

     return property;    
    } 

    public string GetStringProperty(string name) { 
     var property = GetProperty(name); 
     return (string) property.GetValue(this, null); 
    } 

    public T GetProperty<T>(string name) { 
     var property = GetProperty(name); 
     return (T) property.GetValue(this, null); 
    } 
} 

GetPropertyGetStringProperty方法如果該屬性不存在,則拋出ArgumentException

使用範例:

Person person = new Person { 
    ID = "1", 
    FirstName = "First", 
    LastName = "Last", 
    Age = 31    
}; 

Console.WriteLine(person.GetStringProperty("FirstName")); 
Console.WriteLine(person.GetProperty<int>("Age"));