C# 为什么在处理任务时使用私有静态方法

C# 为什么在处理任务时使用私有静态方法,c#,task-parallel-library,C#,Task Parallel Library,此代码取自另一个网站: 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 stat

此代码取自另一个网站:

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
    }
}
使用系统;
使用System.Threading.Tasks;
公共课程{
专用静态Int32和(Int32 n)
{
Int32总和=0;
对于(;n>0;n--)
已检查{sum+=n;}
回报金额;
}
公共静态void Main(){
任务t=新任务(n=>Sum((Int32)n),1000);
t、 Start();
t、 等待();
//获取结果(result属性内部调用Wait)
Console.WriteLine(“总和为:+t.Result);//一个Int32值
}
}
我不理解使用私有静态方法而不是任何其他普通公共方法的目的


谢谢

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


该方法可能是私有的,因为没有理由将其公开。

这是因为您有一个Main方法是
static
,并且您不能从
static
方法调用非静态方法,而不使用该类的make对象,因为非静态方法是用object调用的

如果使Sum方法非静态,则必须在程序类的对象上调用它

private Int32 Sum(Int32 n)
{
      //your code
}
呼叫将更改为

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

你说的是什么方法?私有静态Int32 Sum(Int32 n),因为该方法仅用于程序类,所以这就是为什么它是私有的,并且不能从静态方法调用非静态方法?如果没有对象引用hanks@SriramSakthivel,就不能从静态方法调用非静态方法,真是太好了。