小编Wil*_*iam的帖子

为什么不调用这个 C# 实例构造函数,除非有对非静态成员的引用?

这段代码似乎没有调用Mixed构造函数并打印y = 0

public class Mixed
{
    public int x;
    public static int y;

    public Mixed()
    {
        x = 1;
        y = 1;
    }
}    

public class Program
{
    static Mixed mixed = new Mixed();

    static void Main(string[] args)
    {
        Console.WriteLine("y = " + Mixed.y);

        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,简单地将Main函数修改为如下所示会导致调用构造函数。

static void Main(string[] args)
{   
    Console.WriteLine("x = " + mixed.x);
    Console.WriteLine("y = " + Mixed.y);

    Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)

这打印:

x = 1
y = 1
Run Code Online (Sandbox Code Playgroud)

为什么简单地将此引用添加到非静态字段会导致构造函数被正确调用?创建对象不应该总是导致调用构造函数,而不管该对象稍后在程序中如何使用?

奇怪的是, …

c# static .net-core

5
推荐指数
1
解决办法
279
查看次数

标签 统计

.net-core ×1

c# ×1

static ×1