samedi 27 décembre 2014

Creating a property selector Expression from a string

I'm trying to generate a "Property Selector" from a string.


Let me explain myself a bit with a Real life example:


We have a Class Person with a Name (string) property.


I could manually create a "property selector" like this propertySelector writing:



Expression<Func<Person, string>> propertySelector = x => x.Name;


But I would like to get the same property selector with my method.



var propertySelector = CreatePropertySelectorExpression<Person, string>("Name");


What I have so far is this:



public static Expression<Func<TIn, TOut>> CreatePropertySelectorExpression<TIn, TOut>(string path)
{
Expression exp = Expression.Parameter(typeof(TIn), "x");
foreach (var property in path.Split('.'))
{
exp = Expression.PropertyOrField(exp, property);
}
return exp;
}


But... I've got and invalid cast error!



Cannot implicitly convert type 'System.Linq.Expressions.Expression' to 'System.Linq.Expressions.Expression>'. An explicit conversion exists (are you missing a cast?)



I'm very new to Expressions and I don't know how to continue :(






Aucun commentaire:

Enregistrer un commentaire