繁体   English   中英

通过反射将First()与泛型集合一起使用

[英]Using First() with a generic collection through reflection

假设声明了以下方法:

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

如何使用反射返回泛型集合中第一个元素的属性theProperty的值? (使用Linq的First()方法)。

谢谢

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

为简便起见,省略了错误检查:

return (string) typeof(T).GetProperty(theProperty).GetValue(collection.First(), null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM