3
我有以下表達式類型:如何轉換Expression <Func <MyClass,int >>中的屬性選擇器?
Expression<Func<MyClass, int>>
我怎樣才能將其轉換爲...
Expression<Func<MyClass, object>>
...然後回...
Expression<Func<MyClass, int>>
我有以下表達式類型:如何轉換Expression <Func <MyClass,int >>中的屬性選擇器?
Expression<Func<MyClass, int>>
我怎樣才能將其轉換爲...
Expression<Func<MyClass, object>>
...然後回...
Expression<Func<MyClass, int>>
我懷疑你可以使用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
}
}
這裏有一個相關的問題:http://stackoverflow.com/questions/6698553/how-do-i -translate-AN-表達式樹的一型到一個-不同表達型 –