c# - 具有引用参数/参数或匿名函数的 Func/Action 委托(delegate)

标签 c# delegates lambda inline anonymous-function

我只是想知道,委托(delegate)和内联 lambda 函数的 refout 参数的确切语法是怎样的。

举个例子

如果函数定义为

 public void DoSomething(int withValue) { } 

函数中的委托(delegate)可以通过以下方式创建

 public void f()
 {   
     Action<int> f2 = DoSomething;
     f2(3);
 }

如果将原始函数定义为,该语法如何

 public void DoSomething(ref int withValue) { withValue = 3; } 

最佳答案

您需要为此方法签名定义一个新的委托(delegate)类型:

delegate void RefAction<in T>(ref T obj);

public void F()
{
    RefAction<int> f2 = DoSomething;
    int x = 0;
    f2(ref x);
}

.NET Framework 不包含此类型的原因可能是因为 ref 参数不是很常见,如果为每种可能的组合添加一个委托(delegate)类型,则所需类型的数量会激增。

关于c# - 具有引用参数/参数或匿名函数的 Func/Action 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13923685/

相关文章:

c# - 如何创建继承自TextBox的类

c# - 仅针对一个 namespace 解析 XML

c# - 为什么静态成员首先加载到内存中

c# - C# 和 T-SQL 自带哪些统计函数?

ios - 实现嵌入在两个独立容器 Controller 中的 View 之间的委托(delegate)

iphone - 正确实现委托(delegate)和协议(protocol)

c# - 当我坐在 Console.ReadLine() 上时,委托(delegate)会运行吗?

c++ - 在 Lambda 捕获中构建 intializer_list<string>

Python lambda自组合函数: How to return a function that is repeated n amount of times?

c++ - std::equal_range 与 lambda