mercredi 15 juillet 2020

Issues with calling a static method through a string using reflection

I am making an app which is interfaced with at the command line by typing commands that then call corresponding methods. The thing is, some of these methods are asynchronous, and thus, according to what I've heard, should return Task instead of void, even when their return value is not used (async is not necessary for the program I am making, however a library I am using in some of the methods is asynchronous).

Because of this, I can't use a dictionary of delegates (as far as I know), as they would be different types, so I have tried using reflection.

MethodInfo command = MethodBase.GetCurrentMethod()
    .DeclaringType
    .GetMethod(_commands[args[0]]);
command.Invoke(null, new string[][] { args });

The above snippet is intended to get a static method by its name and then call it with argument string[] args.

According to the documentation I'm looking at, alongside other StackOverflow answers, the first argument should be null if the method being called is static, however I get a NullReferenceException anyway. Why is this, and how do I fix it?





Aucun commentaire:

Enregistrer un commentaire