简体   繁体   English

在编译时获取非静态方法的 MethodInfo

[英]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:对于 static 辅助函数,可以通过使用以下方法获取 MethodInfo 实例来保证编译时安全:

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.使用这个,如果Helpers.MyStaticHelper.DoSomethingUseful要更改它的名称或签名,这将导致编译时错误。 However, it only appears to work for static methods.但是,它似乎只适用于 static 方法。 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)' .对非静态使用类似的方法会给出 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.但是,如果DoSomethingElse被更改,这将面临运行时异常的风险。 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?是否可以为没有实例的方法获得编译时安全的 MethodInfo?

You can use nameof to so ensure the method name is accurate:您可以使用nameof来确保方法名称是准确的:

var myMethodInfo = typeof(Helpers.MyDynamicHelper)
    .GetMethod(nameof(Helpers.MyDynamicHelper.DoSomethingElse));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM