gpt4 book ai didi

c# - 为什么以这种方式初始化会产生编译时错误?

转载 作者:行者123 更新时间:2023-11-30 16:02:16 24 4
gpt4 key购买 nike

这可能看起来有些愚蠢,但谁能告诉我为什么下面的代码会出错?

    class Program
{
static int abc;
abc = 110;

static void Main(string[] args)
{
Console.WriteLine(abc);
}
}

但是如果我像这样进行初始化,它就会运行!

    class Program
{
static int abc = 110;

static void Main(string[] args)
{
Console.WriteLine(abc);
}
}

最佳答案

您必须使用静态初始值设定项来执行您想要执行的操作(如果不只是内联分配),否则您需要在构造函数或方法中分配它。

    class Program
{
static int abc;

static Program(){
abc = 110;
}

static void Main(string[] args)
{
Console.WriteLine(abc);
}
}

检查这个page了解更多信息。

关于c# - 为什么以这种方式初始化会产生编译时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37794893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com