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

本文关键字:字段 属性 类型 反射 何使用 检索 | 更新日期: 2023-09-27 18:11:53

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

我不知道

  • 这是一块田地
  • 这是一处房产
  • 以上任何一种都是私有的或公共的

我不能做假设,所以我希望用反思来解决这个问题。我希望开发人员将这些私人领域。。。但我不能这么认为。

如何查找具有..的类型Foo的所有字段/属性。。说int的?

NET 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));