How to create a custom checkbox Select a lambda expression at runtime to work with subclasses

If I have the following type hierarchy:

abstract class TicketBase { public DateTime PublishedDate { get; set; } } class TicketTypeA:TicketBase { public string PropertyA { get; set; } } class TicketTypeB:TicketBase { public string PropertyB { get; set; } } 

and more TicketTypes : TicketBase

and want to create a function that selects any property, for example. PropertyA from any type of ticket, for example. TicketTypeA

I wrote this function:

  private Func<TicketBase, String> CreateSelect(Type t, String FieldName) { var parameterExp = Expression.Parameter(t, "sel"); var fieldProp = Expression.PropertyOrField(parameterExp, FieldName); var lambda = Expression.Lambda<Func<TicketBase, String>>(fieldProp, parameterExp); return lambda.Compile(); } 

and name it on List<TicketBase> Tickets as follows:

 Type typeToSelectFrom = typeof(TicketTypeA); String propertyToSelect = "PropertyA"; Tickets.Select(CreateSelect(typeToSelectFrom, propertyToSelect)); 

I get the following ArgumentException:

 ParameterExpression of type 'TicketTypes.TicketTypeA' cannot be used for delegate parameter of type 'Types.TicketBase' 

Does anyone know how to fix this?

+2
source share
1 answer

Well, one option is to enable casting, for example

 private Func<TicketBase, String> CreateSelect(Type t, String FieldName) { var parameterExp = Expression.Parameter(typeof(TicketBase), "sel"); var cast = Expression.Convert(parameterExp, t); var fieldProp = Expression.PropertyOrField(cast, FieldName); var lambda = Expression.Lambda<Func<TicketBase, String>>(fieldProp, parameterExp); return lambda.Compile(); } 

So calling CreateSelect(typeof(TicketTypeA), "PropertyA") equivalent to:

 Func<TicketBase, string> func = tb => ((TicketTypeA)tb).PropertyA; 

Obviously, a failure will occur if you apply it to a TicketBase value that refers to (say) a TicketTypeB , but this is difficult to avoid if you have a List<TicketBase> or something similar.

+2
source

Source: https://habr.com/ru/post/1341139/


All Articles