Reputation:
I am trying to invoke Invoke
on a Dispatcher
using the following overload:
public object Invoke(Delegate method, params object[] args);
I want to use named arguments, but I can't seem to find the syntax for the argument with the params modifier. All of the following won't compile:
dispatcher.Invoke(method: () => { }, args: {});
dispatcher.Invoke(method: () => { }, args: new object[0]);
dispatcher.Invoke(method: () => { }, args: null);
dispatcher.Invoke(method: () => { }, args: new object[] {});
object[] foo = {};
dispatcher.Invoke(method: () => { }, args: foo);
dispatcher.Invoke(method: () => { }, args: new[] {"Hello", "World!"});
I found these two questions to which there seems to be no definite answers:
How to set named argument for string.Format?
So my question is: can it be done or not? If yes, how?
UDPATE
Daniel Hilgarth's shows that yes params
can be used with named parameters. I integrated his answer using this pattern:
Action method = () => { };
if (_dispatcher != null)
_dispatcher.Invoke(method: method, args: null);
else
method();
Upvotes: 6
Views: 1998
Reputation: 174299
The following code compiles without problems:
void Main()
{
Invoke(method: () => {}, args: new object[] {});
}
public object Invoke(Action method, params object[] args)
{
return null;
}
I had to change the type of the first parameter from Delegate
to Action
to make it compile, because () => {}
can't be converted to Delegate
.
Alternatively, the following does also compile:
void Main()
{
Action method = () => {};
Invoke(method: method, args: new object[] {});
}
public object Invoke(Delegate method, params object[] args)
{
return null;
}
My assumption is that you never got a compile error about the args
parameter but about the method
parameter saying "Cannot convert from 'lambda expression' to 'System.Delegate'". This problem is solved by either casting the lambda to an Action (Invoke(method: (Action)(() => {}) ...
) or by defining a variable of type Action
that is passed as parameter to the method (see above), because Action
can implicitly be converted to Delegate
.
Upvotes: 3
Reputation: 14919
Have a try;
dispatcher.Invoke(method: () => { }, args: new[] {"Hello", "World!"});
Upvotes: 2