开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜