如何使用反射在运行时构建此c#“Expression”?

时间:2022-03-04 20:48:15

To this day, I have not found a great article about expressions - and how to look at a C# lambda statement and say "oh, that's a blah blah"... so, if you know of a good article, I'd appreciate that as an answer too.

直到今天,我还没有找到一篇关于表达的好文章 - 以及如何查看C#lambda语句并说“哦,这是一个等等等等......”所以,如果你知道一篇好文章,我会很感激这也是一个答案。

Code sample to explain the question

So... given the following c# code:

所以...给出以下c#代码:

public class SomeClass<T>
{
    public TResult SomeMethod<TResult>(Expression<Func<T, TResult>> expression)
    {
        // This is just an example... don't get hung up on this :)
        return default(TResult);
    }
}

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

    public string LastName { get; set; }
}

How do I do this...

我该怎么做呢...

var blah = new SomeClass<Person>();

blah.SomeMethod(p => p.FirstName);

at runtime (using reflection)?

在运行时(使用反射)?

What I expect as an answer

I kinda expect something like this... but I'm sure I'm way off with my choice of expressions.

我有点期待这样的事情...但我确信我选择的表达方式已经过时了。

// By the way, these values are being passed to me... so you
// can't change this part of the question :)
Type personType = typeof(Person);
string propertyName = "FirstName";

// THIS CODE BELOW IS OBVIOUSLY WRONG, BUT YOU GET THE IDEA OF
// WHAT I HOPE TO DO... THIS LINE OF CODE BELOW IS **ALL** I'M
// ASKING HOW TO DO :)
var expression = Expression.MakeUnary(ExpressionType.Lambda,
    Expression.Property(Expression.Parameter(personType, "p"),
    propertyName), typeof(string));

blah.SomeMethod(expression);

2 个解决方案

#1


5  

Try this:

尝试这个:

var functorParam = Expression.Parameter(typeof(Person));
var lambda = Expression.Lambda(
    Expression.Property(functorParam, typeof(Person).GetProperty("FirstName"))
,   functorParam /* <<= EDIT #1 */
);
blah.SomeMethod((Expression<Func<Person,string>>)lambda); /* EDIT #2 */

#2


1  

ExpressionBuilder is the way to go.

ExpressionBuilder是要走的路。

#1


5  

Try this:

尝试这个:

var functorParam = Expression.Parameter(typeof(Person));
var lambda = Expression.Lambda(
    Expression.Property(functorParam, typeof(Person).GetProperty("FirstName"))
,   functorParam /* <<= EDIT #1 */
);
blah.SomeMethod((Expression<Func<Person,string>>)lambda); /* EDIT #2 */

#2


1  

ExpressionBuilder is the way to go.

ExpressionBuilder是要走的路。