我正试图列出该类型中的所有属性,如下图所示。
我正在使用以下方法加载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)
并没有返回所有父类的属性。
我认为你必须删除BindingFlags.DeclaredOnly这个标志,因为这个标志的目的正是为了从你的结果中删除继承的属性。