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

bfl*_*mi3 3 c# reflection expression casting

鉴于以下课程:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

以及以下实施:

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

GetEventsById签名在哪里:

IEnumerable<EventDto> GetEventsById(int id);
Run Code Online (Sandbox Code Playgroud)

我收到错误:

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

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

sir*_*lot 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();
}
Run Code Online (Sandbox Code Playgroud)

表达式在编译时确定,这意味着当我说str => str.Length我正在调用属性时str,编译器会将其解析为a MemberExpression.

如果我改变我的lambda看起来像这样:

Express(str => str.Count());
Run Code Online (Sandbox Code Playgroud)

那么编译器明白,我打电话Count()的str,所以它解析为一个MethodCallExpression...因为它实际上是一个方法.

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

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

(str, startsWith) => str.StartsWith(startsWith)
Run Code Online (Sandbox Code Playgroud)


(1)首先我们需要从构建两个参数开始: (str, 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");
Run Code Online (Sandbox Code Playgroud)


(2)然后在右边,我们需要建立:str.StartsWith(startsWith).首先,我们需要使用反射来结合StartsWith(...)方法的String那个采用类型的单个输入String,像这样:

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


(3)现在我们有了绑定元数据,我们可以使用a MethodCallExpression来实际调用方法,如下所示:

//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 });
Run Code Online (Sandbox Code Playgroud)


(4)现在我们有左侧(str, startsWith)和右侧str.StartsWith(startsWith).现在我们只需将它们加入一个lambda中.最终代码:

// 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"
Run Code Online (Sandbox Code Playgroud)

更新 嘛,也许这样的事情可能有用:

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();
        }
}
Run Code Online (Sandbox Code Playgroud)

更新:遇到意外事故.考虑以下代码:

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

        ...
    }
Run Code Online (Sandbox Code Playgroud)

输入是WPF的简单lambda:

base.SetPropertyChanged(x => x.Visibility);
Run Code Online (Sandbox Code Playgroud)

因为我正在投影Object,我注意到视觉工作室将其转换为a UnaryExpression,我认为这是你遇到的同样问题.如果你设置一个断点并检查实际表达式(在我的情况下),它说x => Convert(x.Visibility).问题是Convert(实际上只是对当前未知类型的强制转换).你所要做的就是删除它(就像我在上面的代码中使用Operand成员一样,你应该全部设置.也许你会拥有你的MethodCallExpression.