c# - Type.GetProperties 方法

标签 c# .net reflection

我有这样一个类:

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/

相关文章:

C# 动态类型初始化器

c# - 按名称获取字段

.net - Encoding.Default与File.ReadAllText中的无编码不同吗?

c# - 从字节值返回特定位作为 bool 值

c# - 不明显的数组索引

c# - 如何清除 WPF 中的图像控件 (C#)

c# - 如何在类似于 phpMyAdmin 的 asp.net 中创建动态表/字段

.net - .NET 的自然语言日期/时间解析器?

java - 使用反射获取 Field 的通用类型

c# - 如何在 Controller 中访问 IApplicationBuilder?