C# - 为什么我可以在没有实例化的类中使用委托?

Joh*_*n V 2 c# field class

我认为委托字段就像其他字段一样,在实例化类之前我不能使用它们.然而:

 class Program
    {

        delegate void lol (int A);
         string myX;

        static void Main(string[] args)
        {
            lol x = ... //works     

            myX //does not exist, 
        }
    }
Run Code Online (Sandbox Code Playgroud)

Sri*_*vel 6

delegate void lol (int A);
Run Code Online (Sandbox Code Playgroud)

委托不是一个字段,它是一个"嵌套类型",所以你可以像任何其他类型一样使用它.

并且引用myX内部Main是非法的,因为myX是实例字段.你需要使用instance.myX在静态方法中使用它(Main() here)

更清楚的是,尝试下面你会意识到你做错了什么

class Program
{
    delegate void lol (int A);
     string myX;
     lol l; 

    static void Main(string[] args)
    {
        l = null; //does not exist
        myX //does not exist, 
    }
}
Run Code Online (Sandbox Code Playgroud)