从给定的Type创建表达式<Func >

我希望通过在代码中构建表达式动态地使用CsvHelper,代码表示给定类型的属性成员访问。

我试图传递这些表达式的方法具有以下签名:

public virtual CsvPropertyMap Map( Expression<Func> expression ) { // } 

因此,您通常会调用它,对于您要映射的任何给定类型,如下所示(对于具有名为’stringProperty’的属性的类型):

 mapper.Map(x => x.StringProperty); 

传入lambda,内部转换为Expression<Func>

我试图使用表达式在代码中创建此表达式。 在编译时它一切正常(因为它返回一个Expression<Func> ),但在运行时我得到一个exception’不是成员访问’。 这是一个代码,它接受一个PropertyInfo对象来表示我想要映射的属性:

  private Expression<Func> CreateGetterExpression( PropertyInfo propertyInfo ) { var getter = propertyInfo.GetGetMethod(); Expression<Func> expression = m => getter.Invoke( m, new object[] { } ); return expression; } 

基本上,我如何在代码中正确构建表达式?

试试看起来像这样的东西:

  public static Expression> GetGetter(string propName) { var parameter = Expression.Parameter(typeof(T)); var property = Expression.Property(parameter, propName); return Expression.Lambda>(property, parameter); } public static Expression> GetGetter(PropertyInfo propInfo) { var parameter = Expression.Parameter(typeof(T)); var property = Expression.Property(parameter, propInfo); return Expression.Lambda>(property, parameter); } 

这是用法的例子:

  private class TestCalss { public int Id { get; set; } } private static void Main(string[] args) { var getter = GetGetter(typeof(TestCalss).GetProperty("Id")).Compile(); Console.WriteLine(getter(new TestCalss { Id = 16 })); }