jeudi 6 mai 2021

Using Reflection on Type T to create Expression

I'm currently exploring the viability to encapsulate some logic that would typically be iterative. Using a 3rd party library it has a generic Html Helper method that allows you to map properties from a Generic T class to a table component. Typically you'd have to write something to the effect of:

HtmlHelper.GenerateTable<ClassName>
.configure(tableDefinition =>{
  // Adding each property you want to render here
  tableDefinition.add(myClassRef => myClassRef.propertyA);
  tableDefinition.add(myClassRef => myClassRef.propertyB);
})

I'm exploring the idea of adding attributes to properties such as a standard Display attribute and then using reflection, adding that property to the container. The add method only accepts an argument of type Expression<Func<T, TValue>>. With my current understanding of reflection I know I can property identify properties that would be applicable by looping through PropertyInfo and checking for the attribute I want using GetCustomAttribute.

What I'm stumped on is if it's possible using reflection to supply the argument type that the add method expects?

I'll throw the helper method logic I've started using so far. My assumption is that this is leading me towards Expression and Lambda classes, but I haven't been able to flesh out anything that works since I don't technically have a TValue.


var t = typeof(T);
List<PropertyInfo> properties = t.GetProperties().ToList();
foreach(var prop in properties)
{
    var attr = (DisplayAttribute[])prop.GetCustomAttributes(typeof(DisplayAttribute), false);
    if (attr.Length > 0)
    {
        // TODO: Call add with expression?
    }
}




Aucun commentaire:

Enregistrer un commentaire