[英]Converting Expression<Func<TProperty>> to Func<TObject, TProperty> where TObject is known
I'm trying to convert an: 我正在尝试转换:
Expression<Func<TProperty>>
to a 到一个
Func<TObject, TProperty>
Where TObject is known and exposes the property expressed by the Expression. TObject是已知的,并公开由Expression表示的属性。 For this I imagine have to manipulate the Expression, combine it with the TObject type parameter in a new Expression, and compile.
为此,我想必须操纵表达式,将其与TObject类型参数组合到新的表达式中,然后进行编译。
Edit: Example input and output 编辑:示例输入和输出
class SomeType
{
public int Number { get; set; }
public Func<TObject, TProperty> FuncConverter<TObject, TProperty>(Expression<Func<TProperty>>)
{
// ???
}
public void test()
{
Func<SomeType, int> outputFunc = FuncConverter<SomeType, int>(inputExpression);
}
}
An expression I expect as input: 我希望作为输入的表达式:
Expression<Func<int>> inputExpression = () => Number;
This expression points to the Number property on SomeType 该表达式指向SomeType上的Number属性
A Func delegate that I expect as output: 我期望作为输出的Func委托:
Func<SomeType, int> outputFunc = type => type.Number;
End Edit 结束编辑
The problem is, I have no idea to how to do that. 问题是,我不知道该怎么做。 I would really appreciate some (references to) accessible information on manipulating Lambda expressions as I have not yet come across any.
我真的很感谢关于操纵Lambda表达式的一些(参考)可访问信息,因为我还没有碰到任何信息。
I found an answer to my question: 我找到了我的问题的答案:
Func<TObject, TProp> Converter<TObject, TProp>(Expression<Func<TProp>> propertyExpression )
{
MemberExpression member = propertyExpression.Body as MemberExpression;
// Get the Property information of the propertyExpression memberExpression
var property = member.Member as PropertyInfo;
// Get the Declaring type information from member expression (equivalent to TObject)
var type = member.Member.DeclaringType;
// Define the source Parameter for the new Func delegate
var param = Expression.Parameter(type, "source");
var source = Expression.Convert(param, type);
// Get the property on the source
var get = Expression.MakeMemberAccess(source, property);
var convert = Expression.Convert(get, typeof(TProp));
// Construct the Expression
var lambda = Expression.Lambda<Func<TObject, TProp>>(convert, param);
// Compile to get the Func delegate type
return lambda.Compile();
}
I found the information here: link 我在这里找到了信息: 链接
Slightly adapted it to solve my problem. 略加调整以解决我的问题。 Thanks to all commenters...
感谢所有评论者...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.