C# Action、Func 可以嵌套或链接吗?

C# Action, Func , Can be Nested or Chaining?

我是 Delegate 的新手(英语也是)。

这是我的示例代码:

var expected_for = new int[Length];

Func<int[], Action<int>> opFactory = res => i => res[i] = arg1[i] + arg2[i];

Parallel.For(0, arg1.Length, opFactory(expected)); // working well

Enumerable.Range(0, arg1.Length).ToList().ForEach(opFactory(expected_foreach));  // working well

         for (int i = 0; i < arg1.Length; i++)
            {
                opFactory(expected_for); //No Error, but expected_for is not changed
            }

Q1。 Func<int[], Action<int>> opFactory = res => i => res[i] = arg1[i] + arg2[i];FuncAction中可以嵌套吗?这对我来说太难理解了。

Q2。 Parallel.For 的第三个参数需要 Action。然后我的 Func 行是 Action?

Q3。如何在 for() 中保存值?

感谢阅读

此致

ICE

委托比你想象的要简单。
让我们取 Func.The 最后一个参数是必须 returned 的结果。
所以你至少需要指定一个泛型参数
例如 Func<int,string> 可以指向接受 int 和 return 字符串的任何方法 在下面的示例中,所有 4 个函数都做同样的事情。

Q1:您可以根据需要将它们复杂化。
Q2:No 动作与 Func.It 不同,因为它是一个接受 Func 的重载 Q3:It 不起作用,因为如果没有 (i),您实际上不会调用名为 opFactory 的 method.You 并忽略其结果

using System;
namespace ConsoleApp1
{

    class Program
    {
        static void Main(string[] args)
        {
            ///lamda statement
            Func<int, string> func4 = i => { return i.ToString(); };

            ///lamda expression (if there is only 1 statement)
            Func<int, string> func3 = i => i.ToString();

            Func<int, string> func2 = delegate (int i) { return i.ToString(); };

            //Just point to an existing method
            Func<int, string> func1 = ToString;
        }

        static string ToString(int arg)
        {
            return arg.ToString();
        }
    }
}

还有一个完整的例子

using System;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApp1
{

    class Program
    {
        static void Main(string[] args)
        {
            int Length = 5;

            var arg1 = Enumerable.Range(10, Length).ToArray();
            var arg2 = Enumerable.Range(100, Length).ToArray();

            var expected = new int[Length];
            var expected_for = new int[Length];
            var expected_foreach = new int[Length];

            Func<int[], Action<int>> opFactory = res => i => res[i] = arg1[i] + arg2[i];

            Parallel.For(0, arg1.Length, opFactory(expected));

            Enumerable.Range(0, arg1.Length).ToList().ForEach(opFactory(expected_foreach));

            for (int i = 0; i < arg1.Length; i++)
            {
                opFactory(expected_for)(i);
            }

            //all 3 tables have the same data 110,112,114,116,118
            Console.ReadLine();
        }
    }
}