通过方法作为参数 [英] Pass method as parameter
问题描述
我在C#中使用的库,其中一种方法要求我将目标方法的字符串名称作为参数传递.
I am using a library in C# where a method requires that I pass the string name of a target method as a parameter.
出于明显的原因,我想避免使用硬编码的字符串,因此,我将编写一个中间util方法,该方法采用一个方法,获取名称(大概是通过反射),并将其输入到库方法中.
I want to avoid using hardcoded strings for obvious reasons, so I will write an intermediate util method that takes a method, gets the name (presumably via reflection) and feeds it into the library method.
我希望中间方法看起来像这样:
I expect the intermediate method to look something like this:
public void CallOtherMethod(???? inputMethod)
{
string methodName = inputMethod.Name; // This gives me the method without the namespace, right?
this.CallFinalMethod(methodName);
}
要这样称呼:
this.CallOtherMethod(this.SomeOtherMethod);
但是,我在确定执行此操作所需的类型时遇到了一些麻烦.
However, I'm having some trouble figuring out the type required to do this.
如何正确定义我的方法?
How can I correctly define my method?
作为旁注,我很乐意将此作为库的扩展方法来编写,但这与库的行为方式完全不兼容.
As a side note, I would happily write this as an extension method to the library, but this doesn't quite work with the way the library behaves.
推荐答案
尝试像这样使用Action
或Func
:
public void CallOtherMethod(Action method)
{
string methodName = method.Method.Name;
method.Invoke();
}
public void AnotherMethod(string foo, string bar)
{
// Do Something
}
致电:
CallOtherMethod( () => AnotherMethod("foo", "bar") );
这篇关于通过方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!