C# Convert method to Action<object>

If I have a method such as:

public void DoSomething(object parm) { }

then within this class I can then do this:

void DefineMethod()
{
    Action<object> someMethod = DoSomething;
}

But how do I set 'someMethod' in classB when 'DoSomething()' is in another classA? Essentially I need to convert the method from ClassA into an Action<object> in classB.

I know I can simply create DefineMethod() with a parameter of type Action<object> to solve the problem. But that is too simple a use case - assume that I want to create an Action<object> for every method in Class A with one call to DefineMethod() in classB (and that call will come from a method in ClassA itself). Essentially I want to loop over the methods in ClassA. I could retrieve methodinfo[] using .GetMethods(), by passing the classA type as a parameter. But I don't know how to convert the method info data to Active<object>.
esc_toe_accountAsked:
Who is Participating?
 
esc_toe_accountAuthor Commented:
I have found the answer for creating an Action delegate from methodinfo (and the appropriate instance)

Action<object> action = delegate(object xyz) { methodinfo.Invoke(classInstance, parameters); }

where of-course parameters only contains one parameter because this is an Action.
0
 
käµfm³d 👽Commented:
There needs to be some common area that has both objects in scope. Then you can define the appropriate public members to assign from one to the other.

For example:


Class Definitions
class ClassA
{
	public void DoSomething(object parm) { }
}

class ClassB
{
	public void DefineMethod(Action<object> DoSomethingMethod)
	{
	    Action<object> someMethod = DoSomethingMethod;
	}
}

Open in new window



Scope Example
class MainClass
{
	public static void Main (string[] args)
	{
		ClassA cA = new ClassA();
		ClassB cB = new ClassB();
		
		cB.DefineMethod(cA.DoSomething);
	}
}

Open in new window

0
 
esc_toe_accountAuthor Commented:
Thanks for responding but I am not looking for a way to pass the method as a parameter. I was concerned that my rushed posting was not clear. Let me restate it in another way.

Within a method in ClassB I want to 'discover' all the methods in ClassA and for each discovered method I want to cast the method as an Action<Object>, The implied caveat on the solution is that I do not pass the method names from ClassA in the parameter list of the call to the method in ClassB. (However, I can pass other pertinent info such as 'this' or class type info).
0
 
esc_toe_accountAuthor Commented:
No one else answered the question
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.