开发者

C# Equivalent of PHP Dynamic Method Calling

In PHP, I can try to call any method that might exist on an object like this:

$object->{$method}();

Where $object is our PHP Object and $method is the name of the method that we want to call. I can dynamically call any method this way.

Is there any C# equivalent to this? Or am I just "doing it wrong"? I have a plugin/module loaded in via Reflection and I'd like to call a meth开发者_C百科od on it that is not defined in the interface.

Thanks!


Contrary to PHP, C# is a statically typed language meaning that types need to be known at compile time. Although such method has been introduced in C# 4.0. It's the dynamic keyword. It allows you to declare a variable of a dynamic type and call whatever method you like on it and the compiler won't protest. The resolution will be done at runtime:

dynamic obj = FetchInstanceFromSomewhere();
obj.Method();

Another more classic method is to use reflection but this could quickly turn into a nightmare.


As answered here, C#4 has the dynamic keyword, that does dynamic method invoking.

If you are on an older version, you can do this using Reflection, but I think it is the wrong way of doing it. The C# way of doing it would be to ensure the plugin loaded has an interface, which contains the methods you need to call.

Anyways, if you need to do it using reflection, here is an example:

Type type = instance.GetType();
MethodInfo m = type.GetMethod("MethodName");
m.Invoke(instance, new object[] {});

This is for a public method taking no arguments.


I have a plugin/module loaded in via Reflection and I'd like to call a method on it that is not defined in the interface

Be carefull though... The cited sentence let me guess that you are doing something wrong. Using reflection 'to the rescue' is a common misconception of many c# users. If the interface in the module was designed without the method you wish to call then there was probably a good reason for this decision. If the module was designed properly you should not be able to call this method anyway - it is either private or internal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜