Can I have an Action<> or Func<> with an out param?

后端 未结 2 1895
不知归路
不知归路 2021-02-03 19:37

I have a method with an out parameter, and I\'d like to point an Action or Func (or other kind of delegate) at it.

This works fine

2条回答
  •  一生所求
    2021-02-03 19:46

    Action and Func specifically do not take out or ref parameters. However, they are just delegates.

    You can make a custom delegate type that does take an out parameter, and use it, though.

    For example, the following works:

    class Program
    {
        static void OutFunc(out int a, out int b) { a = b = 0; }
    
        public delegate void OutAction(out T1 a, out T2 b);
    
        static void Main(string[] args)
        {
            OutAction action = OutFunc;
            int a = 3, b = 5;
            Console.WriteLine("{0}/{1}",a,b);
            action(out a, out b);
            Console.WriteLine("{0}/{1}", a, b);
            Console.ReadKey();
        }
    }
    

    This prints out:

    3/5
    0/0
    

提交回复
热议问题