通过反射将First()与泛型集合一起使用 [英] Using First() with a generic collection through reflection
本文介绍了通过反射将First()与泛型集合一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假定一个声明为以下内容的方法:
Assume a method declared as the following:
public static string GetString<T>(IEnumerable<T> collection, string theProperty)
如何使用反射返回泛型集合中第一个元素的属性theProperty的值?(使用Linq的First()方法).
How can I, using reflection, return the value of property theProperty of the first element in the generic collection? (using Linq's First() method).
谢谢
推荐答案
为简洁起见,省略了错误检查:
Error checking omitted for brevity:
return (string) typeof(T).GetProperty(theProperty).GetValue(collection.First(), null);
这篇关于通过反射将First()与泛型集合一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文