转换表达式<func <tproperty>&gt; to Func <tobject,tproperty =“”>其中TObject已知</tobject,> </func <tproperty>

时间:2012-07-04 08:09:43

标签: c# generics lambda

我正在尝试转换:

Expression<Func<TProperty>>

Func<TObject, TProperty>

知道TObject的位置并公开Expression表示的属性。为此我想象必须操纵Expression,将它与新的Expression中的TObject类型参数结合起来,然后进行编译。

编辑:示例输入和输出

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

我期望作为输入的表达式:

Expression<Func<int>> inputExpression = () => Number;

此表达式指向SomeType上的Number属性

我期望作为输出的Func委托:

Func<SomeType, int> outputFunc = type => type.Number;

结束编辑

问题是,我不知道该怎么做。我非常感谢有关操作Lambda表达式的一些(引用)可访问信息,因为我还没有遇到任何问题。

1 个答案:

答案 0 :(得分:0)

我找到了一个问题的答案:

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();
    }

我在此处找到了相关信息:link

略微适应它来解决我的问题。感谢所有评论者......