c# - 静态字段初始化器

标签 c# static

<分区>

我在我的代码和静态代码初始化器的实现之间陷入困境。现在,我在这里分别调用Main中A类和B类的静态字段“x”。理想情况下,它应该生成如下输出:

A : 0
A.x : 5
B : 0
B.x : 5  

但是,它生成的输出为:

A : 0
B : 0
A.x : 5
B.x : 5  

请解释。

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class A
    {
        public static A _A = new A();
        public static int x = 5;
        public A()
        {
            Console.WriteLine("A : " + x);
        }
    }

    public class B
    {
        public static B _B = new B();
        public static int x = 5;
        public B()
        {
            Console.WriteLine("B : " + x);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("A.x : " + A.x);
            Console.WriteLine("B.x : " + B.x);
            Console.ReadKey();
        }
    }
}

最佳答案

字段的静态初始化以非确定顺序发生,尝试将AB 的构造函数设为静态,并初始化其中的变量。这确保它在第一次使用您的类时按照您指定的顺序进行初始化。

关于c# - 静态字段初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24872729/

相关文章:

c# - 0x800a1391 - JavaScript 运行时错误 : 'Edit_Button_Click' is undefined

c# - DataTable.Compute 不工作

c# - 哈希表的通用版本是什么?

java - static <T extends Number & Comparable<? super 号>>

java - 编写静态 void 方法 - "cannot find symbol"编译错误

c# - 更改另一个线程中使用的实例变量

c# - 如何在 Javascript 中显示 C# 模型列表的某一方面?

Java :Interface Method's Overriding

c++ - 使用相同类型的静态非空指针初始化后,指向自定义类型的静态指针保持 nullptr

c - 驱动函数中的静态全局变量和静态局部变量