c# - 将方法作为参数传递

标签 c# reflection methods

<分区>

我在 C# 中使用一个库,其中一个方法要求我将目标方法的字符串名称作为参数传递。

出于显而易见的原因,我想避免使用硬编码字符串,因此我将编写一个中间 util 方法,它接受一个方法,获取名称(可能通过反射)并将其提供给库方法。

我希望中间方法看起来像这样:

public void CallOtherMethod(???? inputMethod)
{
    string methodName = inputMethod.Name; // This gives me the method without the namespace, right?
    this.CallFinalMethod(methodName);
}

这样调用:

this.CallOtherMethod(this.SomeOtherMethod);

但是,我在确定执行此操作所需的类型时遇到了一些麻烦。

如何正确定义我的方法?

附带说明一下,我很乐意将其作为库的扩展方法编写,但这与库的行为方式不太相符。

最佳答案

尝试像这样使用 ActionFunc:

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") );

关于c# - 将方法作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22455187/

相关文章:

c# - 将 "reference type"作为参数传递给具有 'ref' 键的方法是否有意义?

java - 使用java中的方法时无法循环

c# - 使用 C# 作为后台代码在 Xamarin Forms 的框架内创建 StackLayout

java - BeanUtils 与 ReflectionToStringBuilder 的性能对比(用于 Bean 类)

Java - 注解处理

java - 将整数转换为长整数

java - 当对象传递到多层时检查 null 的最佳方法是什么

c# - 基类继承另一个基类?

c# - dapper 可以反序列化存储为文本的 json 吗?

c# - 避免 CosmosDB 中的 UpsertAsync - 运行更新 SQL 命令