将方法作为参数传递 [英] Pass method as parameter

查看:29
本文介绍了将方法作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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.

推荐答案

尝试像这样使用 ActionFunc:

Try to use Action or Func like this:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆