获取IEnumerable的属性 (其中T是对象)

问题描述 投票:2回答:2

我具有以下功能:

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<object>时,从Type检索T时它没有属性。

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

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

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

c# asp.net reflection system.reflection
2个回答
0
投票

与上述答案相同

GetType()在运行时有效,并且typeof()是编译时运算符

您可以使用此代码访问属性:

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
    foreach (PropertyDescriptor item in properties)
    {
        Console.WriteLine(item.Name);
    }

0
投票

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

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);
© www.soinside.com 2019 - 2024. All rights reserved.