开发者

Invoke a method using a string from Console.Readline

开发者 https://www.devze.com 2023-02-05 03:21 出处:网络
I have source code that does nothing. if (tok[1] == \"?\") { Type _t = typeof(Help); Help _h = new Help();开发者_开发知识库

I have source code that does nothing.

if (tok[1] == "?")
{
    Type _t = typeof(Help);
    Help _h = new Help();开发者_开发知识库
    MethodInfo[] _m = _t.GetMethods();
    foreach (MethodInfo m in _m)
    {
        if (m.Name.CompareTo(tok[0]) == 0)
        {
            m.Invoke(_h, null);
        }
    }
}

It's supposed to invoke a static method from a different class to the if statement, when the user types, say, command ? into the console. The tokenizer works, the method is public, and this is the code I'm using. Any help would be appreciated. Thanks.


If you want to find the static methods you will have to add a BindingFlagsEnum.

MethodInfo[] _m = _t.GetMethods(BindingFlags.Static|BindingFlags.Public );


Use GetMethod instead:

typeof(Help).GetMethod(tok[0]).Invoke(null,null);

Since the method is **static**, you need to pass null in first parameter.

0

精彩评论

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