【问题标题】:How do I build this c# "Expression" at runtime using reflection?如何在运行时使用反射构建这个 c#“表达式”?
【发布时间】:2012-01-22 07:02:21
【问题描述】:

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

解释问题的代码示例

所以...给定以下 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; }
}

我该怎么做...

var blah = new SomeClass<Person>();

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

在运行时(使用反射)?

我期望的答案

我有点期待这样的事情......但我确定我对我的表达方式的选择很不满意。

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

【问题讨论】:

    标签: c# .net reflection lambda expression


    【解决方案1】:

    试试这个:

    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 */
    

    【讨论】:

    • blah.SomeMethod(f);不编译...但我觉得这是非常接近。
    • @TimothyKhouri 如果我正确理解您的意图,SomeMethod 应该采用 Func&lt;T,TResult&gt; functor 而不是 Expression&lt;Func&lt;T,TResult&gt;&gt; expression。这样你就可以写var personsProp = functor(myPerson);之类的东西并得到姓氏。
    • 我调用的方法无法更改...它是我引用的程序集的一部分,因此无法更改它...这就是为什么我问这个问题:)
    • @TimothyKhouri 删除 lambda.Compile 然后传递 lambda。
    【解决方案2】:

    ExpressionBuilder 是要走的路。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      相关资源
      最近更新 更多