C#Func(T)不接受ref类型输入参数

abc*_*bcd 1 c#-4.0

Func(T)可以接受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);
    }
Run Code Online (Sandbox Code Playgroud)

我无法定义一个可以接受ref类型输入参数的func.有人请指教......

SLa*_*aks 5

Func<T>代表不能带ref参数.
您需要创建自己的委托类型,其中包含ref参数.

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


Jar*_*Par 5

扩展 SLAks 的答案。

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

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

T Method<T>() {
  T local = ...;
  ...
  return local;
}
Run Code Online (Sandbox Code Playgroud)

现在考虑一下如果开发人员调用 会发生什么Method<ref int>()。它将产生本地值和返回值,分别是ref. 这将导致无效的 C# 代码。