【问题标题】:.NET reflection - getting the first item out of a reflected collection without casting to specific collection.NET 反射 - 从反射集合中获取第一项而不强制转换为特定集合
【发布时间】:2011-02-08 11:40:50
【问题描述】:

我有一个带有 CustomerContacts 集合的 Customer 对象

IEnumerable<CustomerContact> Contacts { get; set; }

在其他一些代码中,我使用反射并拥有 Contacts 属性的 PropertyInfo

var contacts = propertyInfo.GetValue(customerObject, null);

我知道联系人中至少有一个对象,但我该如何取出呢?我不想将它转换为IEnumerable&lt;CustomerContact&gt;,因为我想让我的反射方法保持动态。我考虑过通过反射调用 FirstOrDefault() - 但不能轻易做到这一点,因为它是一种扩展方法。

有人有什么想法吗?

【问题讨论】:

  • 正如我在问题中提到的,我需要保持反射方法动态。我已经减少了代码以仅显示问题,如果您在上下文中看到它,我怀疑您会建议这样做。

标签: c# reflection collections


【解决方案1】:

如果您真的想避免在代码中提及CustomerContact,您可以这样做:

IEnumerable items = (IEnumerable)propertyInfo.GetValue(customerObject, null);

object first = items.Cast<object>().FirstOrDefault();

【讨论】:

    猜你喜欢
    • 2017-07-18
    • 2010-12-15
    • 1970-01-01
    • 2010-09-11
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多