Type.GetProperties (bindingFlags) не предоставляет поля из родительских классов - PullRequest
0 голосов
/ 28 мая 2020

Я пытаюсь перечислить все свойства в типе, как показано ниже.

Я загружаю файл DLL, используя Assembly.LoadFile(dllFilePath).

Получение всех свойств в сборке, используя 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) не возвращает все свойства родительского класса.

1 Ответ

1 голос
/ 02 июня 2020

Я думаю, вам нужно удалить флаг BindingFlags.DeclaredOnly, потому что цель этого флага состоит в том, чтобы удалить унаследованные свойства из вашего результата.

...