I am trying to list all the properties in the type as shown below.
I am loading the DLL file using Assembly.LoadFile(dllFilePath)
.
Getting all properties in assembly using assembly.GetTypes().ToList()
.
Classes:
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; }
}
Methods:
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);
}
}
In Test 3
all parent class properties are visible when I inspect it.
But typeInstance.GetType().GetProperties(bindingFlags)
doesn't return all parent class properties.
Aucun commentaire:
Enregistrer un commentaire