Execute dynamic method

I am sure that this question was answered, but I had serious problems finding the right combination of keywords to find it.

I am curious to know if something like this can be done:

dynamic someObj = new SomeObject(); var methodName = "someMethodName"; // execute methodName on someObj 

I basically want to know if it can be executed for a dynamic object using a variable that stores the name of the methods.

+6
source share
4 answers

You can do this on any object, not necessarily dynamic , using reflection .

 object obj = new SomeObject(); var meth = obj.GetType().GetMethod("someMethodName"); meth.Invoke(obj, new object[0]); // assuming a no-arg method 

When you use dynamic , you can use any method name identifier, and the compiler will not complain:

 dynamic obj = MakeSomeObject(); obj.someMethodName(); // Compiler takes it fine, even if MakeSomeObject returns an object that does not declare someMethodName() 
+7
source

Well, actually you do not need "someMethodName" in quotation marks. You just do it (full list of programs):

 class Program { static void Main(string[] args) { dynamic obj = new SomeObject(); obj.someMethodName("hello"); } } public class SomeObject { public void someMethodName(string message) { Console.WriteLine(message); } } 

If your method name comes from some kind of evil place like javascript or something else, you can do this:

 class Program { static void Main(string[] args) { dynamic obj = new SomeObject(); var meth = obj.GetType().GetMethod("someMethodName"); meth.Invoke(obj, new object[1]{"hello"}); } } public class SomeObject { public void someMethodName(string message) { Console.WriteLine(message); } } 
+2
source

Based on your comments, the requirement is to be able to call SignalR dynamic client proxy functions using a string. Trying to use reflection for this, i.e.: .GetType().GetMethod(functionName) does not work, because it is not for any dynamic object.

However, this can be done using the Invoke method for a dynamic object.

 var functionName = "alertAllUsers"; var message = "Hello!"; var groupID = "1"; var connection = GlobalHost.ConnectionManager.GetHubContext<SomeHub>(); connection.Clients.Group(groupID).Invoke(functionName, message); 
+1
source
0
source

Source: https://habr.com/ru/post/918137/


All Articles