创建表达式<func <t,object =“”>&gt;通过反射变量</func <t,>

时间:2012-08-25 09:22:35

标签: c# reflection lambda

我创建了以下类:

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

我可以将以下语句设置为方法参数:

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

参数的类型是:

Expression<Func<Person, object>>

现在我要完成的是为反射找到的属性调用SetFieldName方法。想象一下,我有一个PropertyInfo实例(对于Person.LastName)。我尝试使用Lambda方法创建Expression,但是我失败了。

如果你能帮助我,那将是非常好的。

此致 科拉伊

3 个答案:

答案 0 :(得分:2)

// 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);

答案 1 :(得分:1)

你只需要扩展一下弗拉姆的回答:

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 :(得分:0)

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);
    }
}