【问题标题】:Declaration order of types or members in c# [duplicate]c#中类型或成员的声明顺序[重复]
【发布时间】:2021-10-12 04:57:00
【问题描述】:

我完全被 C# 中关于类型或成员声明顺序的一些积极讨论弄糊涂了。

有一个趋势问题,这会产生什么结果以及为什么?

场景 1:

    class Program
    {

        static readonly int A = Method();
        static readonly int B = 42;
        static int Method() => B;

        static void Main()
        {
            Console.WriteLine(A); // 0
        }
    }

如果假设,我更新上面的代码并使其如下所示:

场景 2:

    class Program
    {

        
        static readonly int B = 42;
        static int Method() => B;
        static readonly int A = Method();
        static void Main()
        {
            Console.WriteLine(A); // 42
        }
    }

Scenario 1 的输出是 0Scenario 2 的输出是 42。这个输出是 0 还是 42?

我检查了几个答案,但无法理解这些答案是 0 和 42 的方式和原因。

link 1link 2

【问题讨论】:

标签: c# .net constructor static main


【解决方案1】:

当你写这个时:

class Program
{

    static readonly int A = Method();
    static readonly int B = 42;
    static int Method() => B;

    static void Main()
    {
        Console.WriteLine(A); // 0
    }
}

编译器将为您生成一个静态构造函数,它将初始值分配给您的各个字段。这些赋值的顺序与声明字段的顺序一致:

class Program
{

    static readonly int A;
    static readonly int B;

    static Program()
    {
        A = Method();
        B = 42;
    }

    static int Method() => B;

    static void Main()
    {
        Console.WriteLine(A); // 0
    }
}

当静态构造函数运行时,很明显Method() 被执行,A 被分配给,B 被分配给之前。在为它们分配任何东西之前,字段的初始值为 0。所以Method() 将返回 0。

在第二个场景中遵循相同的逻辑,您会发现它有何不同。

【讨论】:

  • 可能值得补充的是,方法定义的位置无关紧要,它只是存在(我刚刚注意到问题的作者在第二种情况下改变了Method的位置)
猜你喜欢
  • 2012-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多