Why would you use Expression> rather than Func?

后端 未结 10 2154
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 00:32

I understand lambdas and the Func and Action delegates. But expressions stump me.

In what circumstances would you use an Expression

10条回答
  •  萌比男神i
    2020-11-22 00:40

    LINQ is the canonical example (for example, talking to a database), but in truth, any time you care more about expressing what to do, rather than actually doing it. For example, I use this approach in the RPC stack of protobuf-net (to avoid code-generation etc) - so you call a method with:

    string result = client.Invoke(svc => svc.SomeMethod(arg1, arg2, ...));
    

    This deconstructs the expression tree to resolve SomeMethod (and the value of each argument), performs the RPC call, updates any ref/out args, and returns the result from the remote call. This is only possible via the expression tree. I cover this more here.

    Another example is when you are building the expression trees manually for the purpose of compiling to a lambda, as done by the generic operators code.

提交回复
热议问题