C# 创建表达式<;Func<;T、 对象>&燃气轮机;从给定类型
我希望通过在代码中构建表示给定类型的属性成员访问的表达式来动态使用CsvHelper 我试图将这些表达式传递给的方法具有以下签名:C# 创建表达式<;Func<;T、 对象>&燃气轮机;从给定类型,c#,reflection,lambda,expression,C#,Reflection,Lambda,Expression,我希望通过在代码中构建表示给定类型的属性成员访问的表达式来动态使用CsvHelper 我试图将这些表达式传递给的方法具有以下签名: public virtual CsvPropertyMap<TClass, TProperty> Map<TProperty>( Expression<Func<TClass, TProperty>> expression ) { // } 传入lambda,该lambda在内
public virtual CsvPropertyMap<TClass, TProperty> Map<TProperty>( Expression<Func<TClass, TProperty>> expression )
{
//
}
传入lambda,该lambda在内部转换为表达式
我尝试在代码中使用表达式创建此表达式。在编译时一切正常(因为它返回一个表达式
),但在运行时我得到一个异常“nota member access”。下面的代码接受一个PropertyInfo对象,该对象表示我要映射的属性:
private Expression<Func<TModel, object>> CreateGetterExpression( PropertyInfo propertyInfo )
{
var getter = propertyInfo.GetGetMethod();
Expression<Func<TModel, object>> expression = m => getter.Invoke( m, new object[] { } );
return expression;
}
私有表达式CreateGetterExpression(PropertyInfo PropertyInfo)
{
var getter=propertyInfo.getMethod();
Expression=m=>getter.Invoke(m,新对象[]{});
返回表达式;
}
基本上,如何在代码中正确构建该表达式?请尝试以下方法:
public static Expression<Func<T, P>> GetGetter<T, P>(string propName)
{
var parameter = Expression.Parameter(typeof(T));
var property = Expression.Property(parameter, propName);
return Expression.Lambda<Func<T, P>>(property, parameter);
}
public static Expression<Func<T, P>> GetGetter<T, P>(PropertyInfo propInfo)
{
var parameter = Expression.Parameter(typeof(T));
var property = Expression.Property(parameter, propInfo);
return Expression.Lambda<Func<T, P>>(property, parameter);
}
公共静态表达式getter(字符串propName)
{
var参数=表达式参数(typeof(T));
var property=Expression.property(参数,propName);
返回表达式.Lambda(属性,参数);
}
公共静态表达式getter(PropertyInfo propInfo)
{
var参数=表达式参数(typeof(T));
var property=Expression.property(参数,propInfo);
返回表达式.Lambda(属性,参数);
}
这是一个用法示例:
private class TestCalss
{
public int Id { get; set; }
}
private static void Main(string[] args)
{
var getter = GetGetter<TestCalss, int>(typeof(TestCalss).GetProperty("Id")).Compile();
Console.WriteLine(getter(new TestCalss { Id = 16 }));
}
私有类testcals
{
公共int Id{get;set;}
}
私有静态void Main(字符串[]args)
{
var getter=GetGetter(typeof(TestCalss).GetProperty(“Id”)).Compile();
WriteLine(getter(newtestcalss{Id=16}));
}
属性类型实际上是对象吗?另外,如果您已经有了PropertyInfo
对象,为什么不直接调用PropertyInfo.GetValue()
,而不是尝试调用getter方法呢?还有,这里使用反射有什么意义?如果没有一个好的答案,你很难看到你真正想要达到的目标和你面临的具体困难。我和彼得一样担心,但希望这里类似的问题和答案能帮助你。
private class TestCalss
{
public int Id { get; set; }
}
private static void Main(string[] args)
{
var getter = GetGetter<TestCalss, int>(typeof(TestCalss).GetProperty("Id")).Compile();
Console.WriteLine(getter(new TestCalss { Id = 16 }));
}