为什么我不能将Expression Body转换为MethodCallExpression

时间:2013-05-30 13:09:30

标签: c# reflection casting expression

鉴于以下课程:

public class MyClass {

    private readonly UrlHelper _urlHelper;

    // constructor left out for brevity

    // this is one of many overloaded methods
    public ILinkableAction ForController<TController, T1, T2>(Expression<Func<TController, Func<T1, T2>>> expression) {
        return ForControllerImplementation(expression);
    }

    private ILinkableAction ForControllerImplementation<TController, TDelegate>(Expression<Func<TController, TDelegate>> expression) {
        var linkableMethod = new LinkableAction(_urlHelper);

        var method = ((MethodCallExpression) expression.Body).Method;
        method.GetParameters().ToList().ForEach(p => linkableMethod.parameters.Add(new Parameter {
            name = p.Name,
            parameterInfo = p
        }));

        return linkableMethod;
    }
}

以及以下实施:

var myClass = new MyClass(urlHelper);
myClass.ForController<EventsController, int, IEnumerable<EventDto>>(c => c.GetEventsById);

其中GetEventsById有签名:

IEnumerable<EventDto> GetEventsById(int id);

我收到了错误:

  

无法将“System.Linq.Expressions.UnaryExpression”类型的对象强制转换为“System.Linq.Expressions.MethodCallExpression”。

  1. 如何将表达式转换为适当的类型以获取给定表达式的MethodInfo
  2. 在上面的示例中,
  3. TDelegate在运行时为Func<int, IEnumerable<EventDto>>。因为这是Delegate为什么我无法从表达式中获取MethodInfo

2 个答案:

答案 0 :(得分:7)

问题是MethodCallExpression必须实际上是一种方法。考虑:

public static void Main()
{
    Express(str => str.Length);
    Console.ReadLine();
}


static void Express(Expression<Func<String, Int32>> expression)
{
    // Outputs: PropertyExpression (Which is a form of member expression)
    Console.WriteLine(expression.Body.GetType()); 
    Console.ReadLine();
}

表达式是在编译时确定的,这意味着当我说str => str.Length我在str上调用属性时,编译器将其解析为{{1} }}。

如果我改为将lambda改为:

MemberExpression

然后编译器知道我在Express(str => str.Count()); 上调用了Count(),因此它解析为str ...因为它实际上是一种方法。

但请注意,这意味着您无法将表达式从一种类型转换为另一种类型,只不过可以将MethodCallExpression“转换”为String。你可以做一个解析,但我认为你得到的不是真正的对话......

...说,你可以从零开始构建Int32,这在某些情况下是有帮助的。例如,让我们构建lambda:

MethodCallExpression


(1)首先,我们需要从构建两个参数开始:(str, startsWith) => str.StartsWith(startsWith)

(str, startsWith) => ...


(2)然后在右侧,我们需要构建:// The first parameter is type "String", and well call it "str" // The second parameter also type "String", and well call it "startsWith" ParameterExpression str = Expression.Parameter(typeof(String), "str"); ParameterExpression startsWith = Expression.Parameter(typeof(String), "startsWith"); 。首先,我们需要使用反射绑定到str.StartsWith(startsWith) StartsWith(...)方法,该方法采用String类型的单个输入,如下所示:

String


(3)现在我们有了绑定元数据,我们可以使用// Get the method metadata for "StartsWith" -- the version that takes a single "String" input. MethodInfo startsWithMethod = typeof(String).GetMethod("StartsWith", new [] { typeof(String) }); 来实际调用方法,如下所示:

MethodCallExpression


(4)现在我们有左侧//This is the same as (...) => str.StartsWith(startsWith); // That is: Call the method pointed to by "startsWithMethod" bound above. Make sure to call it // on 'str', and then use 'startsWith' (defined above as well) as the input. MethodCallExpression callStartsWith = Expression.Call(str, startsWithMethod, new Expression[] { startsWith }); /和右侧(str, startsWith)。现在我们只需要将它们加入一个lambda中。最终代码:

str.StartsWith(startsWith)

<强>更新 好吧,也许这样的事情可能有用:

// The first parameter is type "String", and well call it "str"
// The second parameter also type "String", and well call it "startsWith"
ParameterExpression str = Expression.Parameter(typeof(String), "str");
ParameterExpression startsWith = Expression.Parameter(typeof(String), "startsWith");

// Get the method metadata for "StartsWith" -- the version that takes a single "String" input.
MethodInfo startsWithMethod = typeof(String).GetMethod("StartsWith", new[] { typeof(String) });

// This is the same as (...) => str.StartsWith(startsWith);
// That is: Call the method pointed to by "startsWithMethod" bound above. Make sure to call it
// on 'str', and then use 'startsWith' (defined above as well) as the input.
MethodCallExpression callStartsWith = Expression.Call(str, startsWithMethod, new Expression[] { startsWith });

// This means, convert the "callStartsWith" lambda-expression (with two Parameters: 'str' and 'startsWith', into an expression
// of type Expression<Func<String, String, Boolean>
Expression<Func<String, String, Boolean>> finalExpression =
    Expression.Lambda<Func<String, String,  Boolean>>(callStartsWith, new ParameterExpression[] { str, startsWith });

// Now let's compile it for extra speed!
Func<String, String, Boolean> compiledExpression = finalExpression.Compile();

// Let's try it out on "The quick brown fox" (str) and "The quick" (startsWith)
Console.WriteLine(compiledExpression("The quick brown fox", "The quick")); // Outputs: "True"
Console.WriteLine(compiledExpression("The quick brown fox", "A quick")); // Outputs: "False"

<强>更新: 遇到意外事故。请考虑以下代码:

class Program
{
        public void DoAction()
        {
            Console.WriteLine("actioned");
        }

        public delegate void ActionDoer();

        public void Do()
        {
            Console.ReadLine();
        }

        public static void Express(Expression<Func<Program, ActionDoer>> expression)
        {
            Program program = new Program();
            Func<Program, ActionDoer> function = expression.Compile();
            function(program).Invoke();
        }

        [STAThread]
        public static void Main()
        {
            Express(program => program.DoAction);
            Console.ReadLine();
        }
}

输入是WPF的简单lambda:

    public static String SetPropertyChanged<T>(Expression<Func<T, Object>> expression)
    {
        UnaryExpression convertExpression = (UnaryExpression)expression.Body;
        MemberExpression memberExpression = (MemberExpression)convertExpression.Operand;
        return memberExpression.Member.Name;

        ...
    }

因为我正在投射base.SetPropertyChanged(x => x.Visibility); ,我注意到visual studio会将其转换为Object,我认为这与您遇到的问题相同。如果你设置一个断点并检查实际表达式(在我的例子中)它会显示UnaryExpression。问题是x => Convert(x.Visibility)(实际上只是对当前未知类型的强制转换)。您所要做的就是删除它(就像我在上面的代码中使用Convert成员一样,您应该已经完成​​了设置。也许您将拥有Operand

答案 1 :(得分:2)

我认为答案比所有这些都简单得多。问题是你的lambda表达式签名是这样的:

Expression<Func<TController, Func<T1, T2>>> expression

所以你委托的签名是:

Func<TController, Func<T1, T2>>
or
Func<T1, T2> function(TController controller){}

该函数将TController作为输入,返回委托(Func<T1, T2>);您传递的实现lambda (c => c.GetEventsById)的签名为:

Expression<Func<TController, T1>> expression

所以你编译的lambda委托签名是:

Func<EventsController, int> 
or
int function(EventsController controller){}

所以你在正文中得到了一个UnaryExpression,因为它代表了委托转换(如果你试图编译/调用-> Expression.Compile().Invoke(),我假设会抛出异常)。使您的签名匹配,您的表达体将成为methodCallExpression。