2009-06-15 148 views
0

與泛型集合首先使用()假設聲明爲如下的方法:通過反射

public static string GetString<T>(IEnumerable<T> collection, string theProperty) 

我如何,使用反射,返回泛型集合中的第一個元素的屬性利人的價值? (使用Linq的First()方法)。

由於

回答

3

錯誤檢查不再贅述:

return (string) typeof(T).GetProperty(theProperty).GetValue(collection.First(), null); 
4
public static string GetString<T>(IEnumerable<T> collection, string theProperty) 
{ 
    return (string)(typeof(T)).GetProperty(theProperty).GetValue(collection.First(), null)); 
}