如何使用反射来检索特定类型的所有字段 and/or 属性?

How can I use reflection to retrieve all the fields and/or properties for a specific Type?

我需要使用反射来检索字段的值或 属性,对于特定类型。

不知道是不是

我无法做出假设,所以我希望使用反射来解决这个问题。我 希望 开发人员将创建这些私有字段......但我不能假设。

我如何找到类型 Foo 的所有 fields/properties 具有.. 说.. int

.NET v 4.0 或 4.5 请。 Linq 也是可以接受的:)

我想要这样的伪代码:

var property = source.GetType()
                     .GetProperties(BindingFlags.GetField | BindingFlags.NonPublic)
                     .Where(x => x.PropertyType == typeof (int))
                     .ToList();

类似的东西

const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
                     BindingFlags.Instance | BindingFlags.DeclaredOnly;
PropertyInfo[] properties = yourType.GetProperties(flags);
FieldInfo[] fields = yourType.GetFields(flags);

var intProperties = properties.Where(x => x.PropertyType == typeof (int));
var intFields = fields.Where(x => x.FieldType == typeof (int));

你也可以这样写(更接近你的例子)

const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
                     BindingFlags.Instance | BindingFlags.DeclaredOnly;

var intProperties = yourType.GetProperties(flags)
                    .Where(x => x.PropertyType == typeof (int));

var intFields = yourType.GetFields(flags)
                .Where(x => x.FieldType == typeof (int));