Type.GetProperties(bindingFlags) 没有提供来自父 类 的字段

Type.GetProperties(bindingFlags) is not giving fields from parent classes

我正在尝试列出类型中的所有属性,如下所示。

我正在使用 Assembly.LoadFile(dllFilePath).

加载 DLL 文件

使用 assembly.GetTypes().ToList() 获取程序集中的所有属性。

类:

public class A
{
    public int Property1 { get; set; }
    public int Property2 { get; set; }
    public int Property3 { get; set; }
    public int Property4 { get; set; }
}

public class B : A
{
    public int Property5 { get; set; }
}

方法:

static void Main()
{
    Assembly assembly = Assembly.LoadFile(dllFilePath);
    List<Type> types = assembly.GetTypes().ToList();
    GetAllProperties(typeof(types.FirstOrDefult(a => a.Name == "B")));
}

private void GetAllProperties(Type type)
{
    BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic
        | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static
        | BindingFlags.FlattenHierarchy;

    // Test 1: No inherited properties.
    PropertyInfo[] propertyInfoList1 = type.GetProperties(bindingFlags);

    List<string> propertyNameList1 = new List<string>();
    foreach (PropertyInfo propertyInfo1 in propertyInfoList1)
    {
        propertyNameList1.Add(propertyInfo1.Name);
    }

    // Test 2: No inherited properties.
    PropertyInfo[] propertyInfoList2 = Activator.CreateInstance(type).GetType().GetProperties(bindingFlags);

    List<string> propertyNameList2 = new List<string>();
    foreach (PropertyInfo propertyInfo2 in propertyInfoList2)
    {
        propertyNameList2.Add(propertyInfo2.Name);
    }

    // Test 3: object has all inherited properties but propertyInfoList doesn't have inherited properties.
    object typeInstance = Activator.CreateInstance(type);
    PropertyInfo[] propertyInfoList3 = typeInstance.GetType().GetProperties(bindingFlags);

    List<string> propertyNameList3 = new List<string>();
    foreach (PropertyInfo propertyInfo3 in propertyInfoList3)
    {
        propertyNameList3.Add(propertyInfo3.Name);
    }
}

Test 3 中,所有父 class 属性在我检查时都可见。

但是 typeInstance.GetType().GetProperties(bindingFlags) 并非 return 所有父 class 属性。

我认为您必须删除标志 BindingFlags.DeclaredOnly,因为该标志的目的正是从结果中删除继承的属性。