'Call a method on a dynamic object by name
I'm trying to create a "wrapper" around a dynamic object so I can keep method names on dynamic object matching the names of the methods in the wrapping class.
What I need to do is provide the helper a dynamic
object, and the name of the method i want to call on it (via [CallerMemberName]
), and the args for the call. I can't figure out how to invoke the call on the dynamic object. How can I do this?
class Program
{
static void Main(string[] args)
{
var dyn = new ClassWithDynamicProperty();
dyn.SendMessage("test");
Console.ReadKey();
}
}
public class ExampleDynamicClass
{
public void SendMessage(string msg)
{
Console.WriteLine(msg);
}
}
public class ClassWithDynamicProperty
{
public ClassWithDynamicProperty()
{
MyDynObject = new ExampleDynamicClass();
}
public dynamic MyDynObject { get; set; }
public void SendMessage(string theMessage)
{
//i want to replace this:
MyDynObject.SendMessage(theMessage);
//with this:
DynamicHelper.CallDynamic(MyDynObject, new object[] { theMessage });
}
}
public static class DynamicHelper
{
public static void CallDynamic(dynamic source, object[] args, [CallerMemberName]string methodName = null)
{
//source.methodName(args); How can i invoke this?
}
}
Solution 1:[1]
Turns out it's not that hard after all. I didn't know if normal reflection would work with dynamic
types. All resources I found for dynamic objects involved overriding TryInvokeMember
, which wasn't an option. Here's missing code:
var method = ((object)dynamicObject).GetType().GetMethod(methodName);
method.Invoke(dynamicObject, args);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |