Type.GetProperties(bindingFlags)没有给出父类的字段

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

我正在使用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中,所有父类属性在我检查时都是可见的。

但是typeInstance.GetType().GetProperties(bindingflags)不会返回所有父类属性。

iCMS 回答:Type.GetProperties(bindingFlags)没有给出父类的字段

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

本文链接:https://www.f2er.com/2257371.html

大家都在问