请说明int a之间是否有任何区别;和int a = new int() [英] please explain if there is any difference between int a; and int a =new int()
问题描述
hi expert
C#中的以下声明之间有什么区别吗?
int a;
int a = new int();
请解释。
谢谢和问候
Divaker
hi expert
Is there any difference between following statement in C#?
int a;
int a=new int();
please explain.
Thanks & Regards
Divaker
推荐答案
行
The line
int a;
声明 int
变量 a
。它必须在使用前初始化。
行
declares the int
variable a
. It must be initialized before use.
The line
int a=new int();
声明并初始化为 0
int
变量 a
。
参见值类型(C#参考) [ ^ ]。
见这里 [ ^ ]
我的猜测是新的int()将生成一个0和int a(没有new)将生成一些奇怪的值,如int max或int min值。
创建一个控制台应用程序并尝试将其打印出来。
See here[^]
my guess is that new int() will generate a 0 and int a (without new) will generate some weird value like int max or int min values.
Create a console application and try to print it out.
class Program {
static void Main(string[] args) {
int a;
int b = new int();
Console.WriteLine("a = " + a);
Console.WriteLine("b = " + b);
Console.ReadLine();
}
}
试过它,甚至不编译。 a未初始化,因此您无法使用它。你需要在使用之前设置一个值。
Just tried it, doesn't even compile. a is uninitialized so you can't use it. You need to set a value before using a.
int a;: allocates an int on stack and does not initialize it.
int a=5;: allocates an int on stack and sets it to 5;
int a=new int();: allocates an int on stack and sets it to 0;
int a=new int(5);: does not compile.
或
你可以看到第二个只是初始化它,第一个初始化和设置。至于生成的IL代码,它们都在一行中初始化
OR
As you can see second one just initialize it and first one initialize and set . As for the IL code generated, they both get initialized in a single line
这篇关于请说明int a之间是否有任何区别;和int a = new int()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!