Rahul W
Rahul W

Reputation: 841

Convert custom delegate type to Action<Object>

I want to convert the below delegate type to Action type, but i am getting runtime error

internal delegate void ExecuteMenuClick(object Sender);

using reflection i am getting the MethodInfo of a method which have same parameters.

void SampleMethod(object Sender){}

Now, i have a command class implementation that takes Action as parameter. I want to create a delegate and pass it to the command class so that it gets invoked.

CommandExecutor loclCommand = new CommandExecutor((Action<object>)Delegate.CreateDelegate(typeof(ExecuteMenuClick), instance, methodinfo);

However, i ended up getting the following error

Unable to cast object of type 'sampleproject.ExecuteMenuClick' to type 'System.Action`1[System.Object]'.

Upvotes: 0

Views: 563

Answers (1)

Sam Harwell
Sam Harwell

Reputation: 99869

You passed the wrong delegate type in the call to Delegate.CreateDelegate. You should use the following instead, which passes typeof(Action<object>), resulting in a delegate of the correct type.

CommandExecutor loclCommand = new CommandExecutor((Action<object>)Delegate.CreateDelegate(typeof(Action<object>), instance, methodinfo);

Upvotes: 1

Related Questions