未分配的不可空变量的值 (C#)
只是好奇。
如果你去:
string myString;
它的值为空。
但如果你问:
int myInt;
这个变量在 C# 中的值是多少?
谢谢
大卫
Just curious.
If you go:
string myString;
Its value is null.
But if you go:
int myInt;
What is the value of this variable in C#?
Thanks
David
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
首先,请注意,这仅适用于字段,不适用于局部变量 - 这些变量在被赋值之前无法读取,至少在 C# 中是这样。事实上,如果您设置了适当的标志,CLR 会将堆栈帧初始化为 0 - 我相信这是默认情况。但它很少被观察到——你必须经历一些糟糕的黑客攻击。
int
的默认值为 0 - 对于任何类型,它本质上是由全零的位模式表示的值。对于值类型,这相当于调用无参数构造函数,而对于引用类型,这相当于 null。基本上,CLR 将内存清零。
这也是
default(SomeType)
为任何类型指定的值。Firstly, note that this is only applicable for fields, not local variables - those can't be read until they've been assigned, at least within C#. In fact the CLR initializes stack frames to 0 if you have an appropriate flag set - which I believe it is by default. It's rarely observable though - you have to go through some grotty hacks.
The default value of
int
is 0 - and for any type, it's essentially the value represented by a bit pattern full of zeroes. For a value type this is the equivalent of calling the parameterless constructor, and for a reference type this is null.Basically the CLR wipes the memory clean with zeroes.
This is also the value given by
default(SomeType)
for any type.int默认为0
default of int is 0
int 的默认值为 0。
有关每种类型的默认值的完整列表,请参阅此处:http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
The default value for int is 0.
See here for the full list of default values per type: http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
下面是 C# 中值类型的默认值表:
http://msdn.microsoft.com/en-us/library/83fhsxwc。 ASPX
引用类型的默认值通常为 null。
Here is a table of default values for value types in C#:
http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx
Reference types default value is usually null.
字符串是引用类型。 Int 是一种值类型。引用类型只是堆栈上指向堆的指针,它可能包含也可能不包含值。值类型只是堆栈上的值,但它必须始终设置为某个值。
String is a reference type. Int is a value type. Reference types are simply a pointer on the stack directed at the heap, which may or may not contain a value. A value type is just the value on the stack, but it must always be set to something.
T
类型的统一变量的值始终为default(T)
。对于所有引用类型,该值为 null,对于值类型,请参阅 @Blorgbeard 发布的链接(或编写一些代码来检查它)。The value for an unitialized variable of type
T
is alwaysdefault(T)
. For all reference types this is null, and for the value types see the link that @Blorgbeard posted (or write some code to check it).