gpt4 book ai didi

c# - 反射泛型列表类型的属性

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:45 25 4
gpt4 key购买 nike

我有一个像下面这样的类

public class Foo<T>
{
public List<T> Items{ get; set; }
}

我有一个上面类的实例,

Foo<Bar> bars = GetBars();

如何使用反射获取 Bar 的属性?

我试试这个

PropertyInfo[] properties = bars.Items.First().GetType().GetProperties();

但我认为,这不是很好的方法,有没有更好的方法呢?

最佳答案

var Properties = bars.GetType().GetGenericArguments()[0].GetProperties();

假设您不知道列表将包含的类型。

如果它总是一个 Bar 然后使用 typeof(Bar).GetProperties();

关于c# - 反射泛型列表类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6294030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com