lundi 30 janvier 2023

c# Get all properties of an inherited class in a function using generic type

I have a function that converts a DataTable to a List of an object. I use reflection to get the properties of the type T given.

public static List<T> ConvertToList<T> (DataTable dt)
{
    List<string> columnNames = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName.ToLower()).ToList();
    System.Reflection.PropertyInfo[] properties = typeof(T).GetProperties();
    ... (code to create the List from the DataTable)
}

I use it this way :

DataTable FooTable = BD_SolEx.GetFoo();

It gets a DataTable. Column names should match the property names of the object I want. For this example, let's consider that the column names are ID, Name.

ListFoo = new ObservableCollection<Foo>(CommonMethods.ConvertToList<Foo>(FooTable));

with the Foo class written like

public class Foo
{
    public int ID { get; set; }
    public string Name { get; set; }
}

So with ConvertToList, I get the DataTable column names with the first instruction. I get the type T property names with the second instruction. Then I do my other operations to get the List from the DataTable, but I don't have any problem with this part.

And I get my List of Foo items with their ID and Name.

It works well until I try to pass an inherited class. In this case, I only get the parent class property and none of the child's one.

For example, if I create :

public class FooChild : Foo
{
    public bool IsFoo;
}

and use it with

DataTable FooTable = BD_SolEx.GetFooChild();
ListPN = new ObservableCollection<FooChild>(CommonMethods.ConvertToList<FooChild>(FooTable));

I don't get IsFoo field in the list of my fields. I checked my generic type is ConvertToList function and T is type of FooChild.

I tried different Flags (System.Reflection.BindingFlags.Public, System.Reflection.BindingFlags.Instance, System.Reflection.BindingFlags.DeclaredOnly...) but none of them gave me the result I wanted. Am I missing something, or is it the intended way of reflection to work ?





Aucun commentaire:

Enregistrer un commentaire