如何在Expression <func <myclass,int =“”>&gt;?</func <myclass,>中转换属性选择器

时间:2011-08-01 19:05:26

标签: c# linq expression

我有以下表达式类型:

Expression<Func<MyClass, int>>

如何将其转换为...

Expression<Func<MyClass, object>>

......然后回到......

Expression<Func<MyClass, int>>

1 个答案:

答案 0 :(得分:5)

我怀疑你可以使用Expression.Convert

Expression<Func<MyClass, int>> original = ...;

var conversion = Expression.Lambda<Func<MyClass, object>>(
        Expression.Convert(original.Body, typeof(object)),
        original.Parameters);

var conversionBack = Expression.Lambda<Func<MyClass, int>>(
        Expression.Convert(conversion.Body, typeof(int)),
        original.Parameters);

编辑:好的,看起来就像它有效:

using System;
using System.Linq;
using System.Linq.Expressions;

class Test
{
    static void Main()
    {
        Expression<Func<string, int>> original = x => x.Length;
        var conversion = Expression.Lambda<Func<string, object>(
              Expression.Convert(original.Body, typeof(object)),
              original.Parameters);

        var conversionBack = Expression.Lambda<Func<string, int>>(
              Expression.Convert(conversion.Body, typeof(int)),
              original.Parameters);

        Console.WriteLine(conversion); // x => Convert(x.Length)
        Console.WriteLine(conversionBack); // x => Convert(Convert(x.Length))

        Console.WriteLine(conversion.Compile()("Hello")); // 5
        Console.WriteLine(conversionBack.Compile()("Hello")); // 5
    }
}