为什么使用 Task 时使用私有静态方法

Why private static method is used when working with Task

此代码已从另一个网站获取:

using System;
using System.Threading.Tasks;
public class Program {

    private static Int32 Sum(Int32 n)
    {
        Int32 sum = 0;
        for (; n > 0; n--)
        checked { sum += n; } 
        return sum;
    }

    public static void Main() {
        Task<int32> t = new Task<int32>(n => Sum((Int32)n), 1000);
        t.Start();
        t.Wait(); 

        // Get the result (the Result property internally calls Wait) 
        Console.WriteLine("The sum is: " + t.Result);   // An Int32 value
    }
}

我不明白使用私有静态方法而不是任何其他普通 public 方法的目的。

谢谢

该方法是静态的,因为它是从静态上下文中使用的,所以它不能是非静态的。

该方法可能是私有的,因为没有理由让它成为私有的 public。

这是因为您的 Main 方法是 static 并且您不能从 static 方法调用非静态方法而不创建那个 class 的对象,因为非静态方法是用对象调用。

如果使 Sum 方法成为非静态的,您将不得不在程序的对象上调用它 class

private Int32 Sum(Int32 n)
{
      //your code
}

调用将更改为

Task<Int32> t = new Task<Int32>(n => new Program().Sum((Int32)n), 1000);