【问题标题】:Why private static method is used when working with Task为什么在使用 Task 时使用私有静态方法
【发布时间】:2015-05-28 19:57:22
【问题描述】:

此代码取自另一个网站:

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
    }
}

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

谢谢

【问题讨论】:

  • 你说的是什么方法?
  • 私有静态 Int32 Sum(Int32 n)
  • 因为该方法仅适用于程序类,所以它是私有的

标签: c# task-parallel-library


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这是因为你的 Main 方法是 static 并且你不能从 static 方法调用非静态方法,而不是该类的对象,因为非静态方法是用对象调用的。

    如果将 Sum 方法设为非静态方法,则必须在 Program 类的对象上调用它

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

    调用会改成

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

    【讨论】:

    • 你不能从静态方法调用非静态方法?应该是你不能从静态方法调用非静态方法 没有对象引用
    • 谢谢@SriramSakthivel,你真好。
    猜你喜欢
    • 2013-05-08
    • 1970-01-01
    • 2013-11-12
    • 2012-03-28
    • 2011-02-09
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 2018-10-27
    相关资源
    最近更新 更多