mardi 20 septembre 2022

Getting MethodInfo at compile time for a non-static method

I'm working on a program that calculates expressions at runtime based on a set of inputs, then executes those remotely. This requires creating expressions dynamically that call different helper functions.

For static helper functions, compile-time safety can be guaranteed by using the following to get a MethodInfo instance:

var myMethodInfo = ((Func<int, int>) Helpers.MyStaticHelper.DoSomethingUseful).Method

Using this, if Helpers.MyStaticHelper.DoSomethingUseful were to change it's name or signature, this would result in a compile-time error. However, it only appears to work for static methods. Using a similar approach for non-static gives a CS0120 An object reference is required for the nonstatic field, method, or property 'Helpers.MyDynamicHelper.DoSomethingElse(int, int)'.

A workaround is possible by using something like this:

var myMethodInfo = typeof(Helpers.MyDynamicHelper).GetMethod("DoSomethingElse")

However this risks a runtime exception if DoSomethingElse is altered. I'm aware it's not possible to invoke the method without an instance, but these instances are needed for collecting and caching prerequisite data, so any instance created before executing the expression would be incorrect.

Is it possible to get a compile-time safe MethodInfo for the method without an instance?





Aucun commentaire:

Enregistrer un commentaire