Reputation: 2996
Let's say I have a method with the following signature:
public string Foo(Expression expression)
{
...
}
Is it possible to call this method directly, without using proxy methods, and if it is, how?
As a bonus question (to understand why am I trying to do this), is it possible to declare a single method (without overloads) which will be called in all these cases:
Foo(P p => "");
Foo((P p, Q q) => "");
Foo((P p, Q q, R r) => "");
The reason I'm trying to write this in a single method is because I'm only interested in the lambda expression parameter to parse it in some way, not to execute it.
Upvotes: 1
Views: 165
Reputation: 101473
To call this method directly you need to cast expression you pass to specific expression delegate type. For example:
Foo((Expression<Func<P, string>>) ((P p) => ""));
Foo((Expression<Func<P, Q, string>>) ((P p, Q q) => ""));
Foo((Expression<Func<P, Q, R, string>>) ((P p, Q q, R r) => ""));
Expression<Func<P, string>> x = (P p) => "";
Foo(x); // also fine
The reason is otherwise compiler cannot infer type of delegate to use. Expression (P p) => ""
has no type by itself, type is determined by the context. If you use it in context where delegate is expected, and it's compatible - it will be a delegate:
Func<P, string> x = (P p) => "";
MyDelegate x = (P p) => "";
If you use it in context where expression tree of specific delegate type is expected - it will be expression tree:
Expression<Func<P, string>> x = (P p) => "";
But in your case - its type cannot be inferred. It can be Expression<Func<P, string>>
, Expression<MyCustomDelegate>
or anything else. Different delegate types are not the same, even if they have the same signature. So you have to tell it explicitly.
Upvotes: 4
Reputation: 85
Declare a delegate
with the params
keyword.
Example:
public delegate void ParamsAction(params object[] args);
Then:
public void Foo(object[] args)
{
...
}
To use:
ParamsAction action = Foo;
action(p);
action(p, q);
action(p, q, r);
or:
ParamsAction action1 = p => "";
ParamsAction action2 = p, q => "";
ParamsAction action3 = p, q, r => "";
Upvotes: 0
Reputation: 534
yes, You can use as follows,
Foo(Expression<Func<TEntity, bool>> query)
{
// implementation
}
call it as
Foo((x=> x.bar == 1));
you don't need to use overloads in above-mentioned method calls. use this method instead and pass whatever the lambda you want.
hope it helps :)
Upvotes: 0