我有这样一个类:
class ItemList
{
Int64 Count { get; set; }
}
当我写这个的时候:
ItemList list = new ItemList ( );
Type type = list.GetType ( );
PropertyInfo [ ] props = type.GetProperties ( );
我得到一个空的 props 数组。
为什么?是因为 GetProperties 不包含自动属性吗?
最佳答案
问题是默认情况下 GetProperties 只会返回公共(public)属性。在 C# 中,默认情况下成员不是公共(public)的(我相信它们是内部的)。试试这个吧
var props = type.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);
BindingFlags 枚举相当灵活。上述组合将返回该类型的所有非公共(public)实例属性。不过,您可能想要的是所有实例属性,而不考虑可访问性。在这种情况下,请尝试以下操作
var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var props = type.GetProperties(flags);
关于c# - Type.GetProperties 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1246230/