Invoke a method using a string from Console.Readline
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.
加载中,请稍侯......
精彩评论