开发者

.NET reflection : How do I invoke a method via reflection that returns array of objects?

开发者 https://www.devze.com 2022-12-15 01:41 出处:网络
Had a quick question.. Googled but nothing worthwhile found.. I have a simple type like shown below. public class DummyClass

Had a quick question.. Googled but nothing worthwhile found..

I have a simple type like shown below.

public class DummyClass
{
    开发者_StackOverflowpublic string[] Greetings()
    {
         return new string[] { "Welcome", "Hello" };
    }
}

How can I invoke the "Greetings" method via reflection? Note the method returns array of strings.


Nothing special is required to invoke this kind of method:

object o = new DummyClass();

MethodInfo method = typeof(DummyClass).GetMethod("Greetings");
string[] a = (string[])method.Invoke(o, null);


Here is the code you need to call a method using reflection (keep in ind - the MethodInfo.Invoke method' return type is "Object"):

    DummyClass dummy = new DummyClass();

    MethodInfo theMethod = dummy.GetType().GetMethod("Greetings", BindingFlags.Public | BindingFlags.Instance);
    if (theMethod != null)
    {
        string[] ret = (string[])theMethod.Invoke(dummy, null);
    }
0

精彩评论

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