【问题标题】:Getting properties of IEnumerable<T> (where T is object)获取 IEnumerable<T> 的属性(其中 T 是对象)
【发布时间】:2020-04-20 00:38:12
【问题描述】:

我有以下功能:

public IEnumerable<string> PropertiesFromType<T>(IEnumerable<T> input)

根据类型(T),我想获取属性的名称。

我尝试了以下方法:

var properties = typeof(T).GetProperties();
//var properties = input.GetType().GetGenericArguments()[0].GetProperties(); // Doesn't work either
foreach (var item in properties)
{
    Console.WriteLine(item.Name);
}

// By input it does work
var inputProperties = input.First().GetType().GetProperties();
foreach (var item in inputProperties)
{
    Console.WriteLine(item.Name);
}

当向函数发送匿名IEnumerable&lt;object&gt; 时,从T 检索Type 时它没有任何属性。

但是,当使用IEnumerable 中某个项目的Type 时,它确实具有属性。

如建议:How to get the type of T from a member of a generic class or method? 使用 GetGenericArguments 函数既不返回属性。

示例:https://dotnetfiddle.net/Widget/uKzO6H

编辑: 我想我想说的是:是否有可能通过使用T 在没有实例的情况下在IEnumerable 中获取匿名对象的Type

我现在意识到这是不可能的,因为对于匿名对象,T 将永远是 object

【问题讨论】:

  • foreach (string value in Enum.GetNames(typeof(T)))
  • 这能回答你的问题吗? When and where to use GetType() or typeof()?
  • @PavelAnikhouski 不幸的是没有
  • @VDWWD 请参阅 Pavel Anikhouski 回答为什么这不起作用
  • 如果您的意思是匿名类型,那么不,它们具有与常规类型一样的适当属性。换句话说,如果你给它一个你构造为new { A = 42, B = "Meaning of life" }的对象集合,那么你会在T上找到属性A和B。如果你的意思是dynamic或者只是object,那么你是对的,你不能通过查看集合的类型来推断每个对象的属性,你需要查询每个对象的类型。

标签: c# asp.net reflection system.reflection


【解决方案1】:

我不确定这是否是您想要的,但下面的方法采用列表的第一个元素并返回它的属性。

public IEnumerable<string> PropertiesFromType<T>(IEnumerable<T> input)
{
    var item = input.First();
    var properties = new List<string>();

    foreach (PropertyInfo property in item.GetType().GetProperties())
    {
        properties.Add(property.Name);
    }

    return properties;
}

使用示例

public class Book
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime PublishDate { get; set; }
}

var PropertyList = PropertiesFromType<Book>(MyListOfBooks);

【讨论】:

  • 感谢您的帮助,这与我试图实现的目标很接近,但这似乎是不可能的(匿名对象的属性,因为 IEnumerable 中的每个元素可能不同)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
相关资源
最近更新 更多