c#混淆中的变量范围

Joh*_*son 1 c#

阅读关于线程的MSDN https://msdn.microsoft.com/en-us/library/7a2f3ay4%28v=vs.90%29.aspx我在代码中有这样一个混乱:

public class Worker
{

    public void DoWork()
    {
        while (!_shouldStop) // #1 Like here.
        {
            Console.WriteLine("worker thread: working...");
        }
        Console.WriteLine("worker thread: terminating gracefully.");
    }
    public void RequestStop()
    {
        _shouldStop = true; // #2 And here.
    }

    private volatile bool _shouldStop; 
}
Run Code Online (Sandbox Code Playgroud)

如何在声明变量_shouldStop之前使用它?检查上面的#1和#2.

Eri*_*ert 6

如何在声明变量_shouldStop之前使用它?

与C系列中的许多其他语言不同,C#不要求在使用之前声明命名实体. 必须在使用本地之前声明它们,但可以按任何顺序声明和使用类,字段,事件,属性等.

C#还要求在读取之前分配本地,但在读取之前不需要分配其他变量.字段,数组元素等在创建时分配了默认值.