反射

2009-06-15 21 views
0

を通じてジェネリックコレクションで最初に()を使用すると、次のように宣言されたメソッドと仮定します反射

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

どのように私は、リフレクションを使用して、ジェネリックコレクションの最初の要素の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)); 
}