关于func:C#-如何传递对需要out变量的函数的引用?

C# - How can I pass a reference to a function that requires an out variable?

1
2
3
4
5
6
7
8
9
10
public class Foo
{
    public void DoFoo()
    {
       int x;
       var coll = TheFunc("bar", out x);
    }

    public Func<string, int, ICollection<string>> TheFunc { get; set; }
}

错误:"参数2不应与'out'关键字一起传递。"

1
2
3
4
5
6
7
8
9
10
public class Foo
{
    public void DoFoo()
    {
       int x;
       var coll = TheFunc("bar", out x);
    }

    public Func<string, out int, ICollection<string>> TheFunc { get; set; }
}

错误:"无效的方差修饰符。只能将接口和委托类型参数指定为变量。"

如何在此函数中获取out参数?


定义一个委托类型:

1
2
3
4
5
6
7
8
9
10
11
12
public delegate ICollection<string> FooDelegate(string a, out int b);

public class Foo
{
    public void DoFoo()
    {
       int x;
       var coll = TheFunc("bar", out x);
    }

    public FooDelegate TheFunc { get; set; }
}

您需要创建自己的代表:

1
delegate ICollection<string> MyFunc(string x, out int y);