c# - 在 C# 中将 Action 委托(delegate)作为参数传递

标签 c# delegates

我有一个方法接受 Action 委托(delegate)并执行给定的方法,如下所示:

public void ExpMethod(Action inputDel)
{
    inpuDel();
}

我可以像这样调用上面给定的方法:

ExpMethod(() => {/*do something that matters*/});

一切正常。到目前为止,一切都很好。现在我想要一个将通用 Action 委托(delegate)作为输入参数的方法 - 如下所示:

public void ExpGenMethod(Action<string,int> inputDel)
{
    // I don't know how to call the supplied delegate as it requires parameters
}

此外,我试图以这种方式调用此 ExpGenMethod:

ExpGenMethod(("Hi",1) => {/*do something that makes sense*/});

但它显示语法错误。请让我知道在这种情况下如何使用通用操作委托(delegate)?

最佳答案

委托(delegate)的全部意义在于拥有一个指向方法的指针。因此,在声明它时将参数传递给它是没有意义的。而是在执行委托(delegate)的方法中为您的委托(delegate)传递参数,在您的例子中是在 ExpGenMethod 中:

你应该这样做:

public void ExpGenMethod(Action<string,int> inputDel)
{
    inputDel("Hi", 1);
}

然后这样调用它:

ExpGenMethod((x, y) => {/*do something that makes sense*/});

当执行该委托(delegate)时,x 的计算结果为 "Hi"y 的计算结果为 1

关于c# - 在 C# 中将 Action 委托(delegate)作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41869951/

相关文章:

c# - 如何打印表格的特定区域?

c# - 这样的集合是否存在(Dictionary 和 HashSet 的功能)?

c# - 在 C# 多播委托(delegate)中使用多播

c# - 如何使用类拦截委托(delegate)调用

c# - 安装 .NET Framework 4.5 后 HttpContext.Current.User 为空

c# - 标签大小总是 NaN?

c# - 如何将字符串数组更改为不使用循环子句的字符串?可以用LINQ实现吗?

ios - UICollectionViewCell 与它的 UICollectionViewController 对话

ios - 与一名委托(delegate)和许多发件人的协议(protocol)?

c# - 通过评论禁用 Resharper