Type.GetProperties 方法给出空数组

问题描述 投票:0回答:1

我有一堂这样的课:

class ItemList
{
    Int64 Count { get; set; }
}

当我写下这个:

ItemList list = new ItemList ( );
Type type = list.GetType ( );
PropertyInfo [ ] props = type.GetProperties ( );

我得到一个空的道具数组。

为什么?是因为

GetProperties()
不包含自动属性吗?

c# .net reflection
1个回答
18
投票

问题是 GetProperties 默认情况下只会返回公共属性。在 C# 中,默认情况下成员不是公共的(我相信它们是内部的)。试试这个吧

var props = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);

BindingFlags 枚举相当灵活。上述组合将返回该类型的所有非公共实例属性。不过,您可能想要的是所有实例属性,无论可访问性如何。在这种情况下,请尝试以下方法

var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var props = type.GetProperties(flags);
© www.soinside.com 2019 - 2024. All rights reserved.