Creating an expression <Func <T, object >> using reflection

I created the following class:

public class Person { public string FirstName { get; set; } public string LastName { get; set; } } 

I can set the following statement in a method parameter:

 myClass.SetFieldName<Person>(p => p.LastName); 

Parameter Type:

 Expression<Func<Person, object>> 

Now what I'm trying to do is call the SetFieldName method on the property found by reflection. Imagine I have an instance of PropertyInfo (for Person.LastName). I tried to create an expression using its Lambda method, but I failed.

So it would be very nice if you can help me with this.

Regards, Korai

+6
source share
3 answers
 // reflected field name string fieldName = "LastName"; // create the parameter of the expression (Person) ParameterExpression param = Expression.Parameter(typeof(Person), string.Empty); // create the expression as a get accessor of a particular // field of the parameter (p.LastName) Expression field = Expression.PropertyOrField(param, fieldName); 
+2
source

You just need to expand the Flemish answer a bit:

 using System; using System.Linq.Expressions; using NUnit.Framework; public class Person { public string FirstName { get; set; } public string LastName { get; set; } } public static class ExpressionBuilder { public static Expression<Func<TClass, TProperty>> Build<TClass, TProperty>(string fieldName) { var param = Expression.Parameter(typeof(TClass)); var field = Expression.PropertyOrField(param, fieldName); return Expression.Lambda<Func<TClass, TProperty>>(field, param); } } [TestFixture] public class Test { [Test] public void TestExpressionBuilder() { var person = new Person { FirstName = "firstName", LastName = "lastName" }; var expression = ExpressionBuilder.Build<Person, string>("FirstName"); var firstName = expression.Compile()(person); Assert.That(firstName, Is.EqualTo(person.FirstName)); } } 
+2
source
 public static class LambdaExpressionExtensions { public static Expression<Func<TInput, object>> ToUntypedPropertyExpression<TInput, TOutput> (this Expression<Func<TInput, TOutput>> expression) { var memberName = ((MemberExpression)expression.Body).Member.Name; var param = Expression.Parameter(typeof(TInput)); var field = Expression.Property(param, memberName); return Expression.Lambda<Func<TInput, object>>(field, param); } } 
0
source

All Articles