【问题标题】:C# Func(T) not accepting ref type input parameterC# Func(T) 不接受 ref 类型输入参数
【发布时间】:2022-04-19 22:01:27
【问题描述】:

Func<...> 可以接受 C# 中通过引用传递的参数吗?

static void Main()
{
    Func<string,int, int> method = Work;
    method.BeginInvoke("test",0, Done, method);
    // ...
    //
}
static int Work(ref string s,int a) { return s.Length; }
static void Done(IAsyncResult cookie)
{
    var target = (Func<string, int>)cookie.AsyncState;
    int result = target.EndInvoke(cookie);
    Console.WriteLine("String length is: " + result);
}

我无法定义一个可以接受ref 输入参数的Func&lt;...&gt;

【问题讨论】:

  • 为什么你认为你需要一个ref 参数?

标签: c#-4.0


【解决方案1】:

Func&lt;T&gt; 代表不能接受 ref 参数。
您需要创建自己的委托类型,该类型采用 ref 参数。

但是,您首先不应该在这里使用ref

【讨论】:

【解决方案2】:

扩展 SLaks 答案。

Func&lt;T&gt; 系列委托是通用的,允许您自定义参数和返回的类型。虽然ref 有助于 C# 的类型系统,但它实际上并不是 CLR 级别的类型:它是一个存储位置修饰符。因此,不可能使用通用实例化来控制特定位置是否为ref

如果可能的话,很容易产生完全无效的代码。考虑以下

T Method<T>() {
  T local = ...;
  ...
  return local;
}

现在考虑如果开发人员调用Method&lt;ref int&gt;() 会发生什么。它将产生一个本地值和返回值ref。这将导致无效的 C# 代码。

【讨论】:

    猜你喜欢
    • 2011-06-24
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 2019-02-16
    • 2016-07-02
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多