Store a dictionary of methods with an unknown signature called with reflection

I want to have a dictionary that uses strings as keys and something that represents methods , all of which can have different signatures , as values. From this, something I should have access to MethodInfo and an instance of the object if the method is not static, so that later I can find it by name and call it using reflection.

I thought that Delegate would do, but I cannot find a way to apply a static or instance method to Delegate . I could also create my own class or structure that has an object and MethodInfo , but if so, users of my class would have to disconnect MethodInfo from any method that it wants to add to my dictionary, and it would need to add a Reflection link everywhere (instead of just skipping the method itself or something like (Delegate)myMethod ). Is there any way to do this?

+4
c #
source share
3 answers

If you do not mind specifying the type of delegate each time you add it to the dictionary, you can use Delegate :

 void A() {} string B(string arg) { return arg; } void Test() { var dict = new Dictionary<string, Delegate>(); dict.Add("A", new Action(A)); dict.Add("B", new Func<string, string>(B)); } 
+2
source share

Looks like you just want to have a Dictionary<string, Action> that you can hook into lambda functions:

 var actions = new Dictionary<string, Action>(); actions.Add("Foo", () => Console.WriteLine("Bar!")); Car myCar = new Car(); actions.Add("Vroom", () => myCar.Drive()); actions["Foo"](); //prints "Bar!" actions["Vroom"](); //invokes myCar.Drive 

Thus, all the various signatures, or object references, or static methods or something else are processed by the lambda and its closure semantics.

If you want to pass any context or input to a set, you can provide an untyped context object that you can use when registering a method. Instead of having an Action without parameters, you would use an Action<object> instead:

 var actions = new Dictionary<string, Action<object>>(); var JuanLuisSoldi = new Person(); actions.Add("Lunch Time", context => JuanLuisSoldi.Eat((Food)context)); Food lunch = new Apple(); actions["Lunch Time"](lunch); 
+2
source share

There are many ways, this is one way:

 public class SomeClass { public IDictionary<string, Action> ActionRegistry { get; set; } public void SomeMethod() { // Registering an action that doesn't use reflection: ActionRegistry.Add("SomeAction", () => { Console.WriteLine("Hello");}); // Registering an action that uses reflection object objectInstance; = ... Type type; = ... string methodName; = ... object[] arguments; = ActionRegistry.Add("SomeAction2", () => { type.GetMethod(methodName).Invoke(objectInstance, arguments); }); // Invoking: ActionRegistry["SomeAction2"](); } } 

You can consider lambda / action as adapters. I often use similar dictionaries when thinking.

+1
source share

All Articles