c#:未实例化对象的默认值是什么?
本文关键字:默认值 是什么 对象 实例化 | 更新日期: 2023-09-27 18:15:50
我有一个关于c#默认值的快速问题。
对象未实例化时的默认值是什么?
下面是一个例子:
public class Example
{
public Example() { Console.WriteLine("Content!"); }
}
public class MainClass
{
// obj = ???
Example obj;
}
规则很简单
- 包含的局部变量根本没有初始化,因此包含垃圾。
局部变量不会自动初始化,因此没有默认值。
https://msdn.microsoft.com/en-us/library/aa691170 (v = vs.71) . aspx
- 字段通过默认值(零)初始化:
字段的初始值,无论是静态字段还是静态字段实例字段,是默认值
https://msdn.microsoft.com/en-us/library/aa645756 (v = vs.71) . aspx
例如 public class Example {
bool m_Bool; // default value == false
int m_Int; // default value == 0
double m_Double; // default value == 0.0
string m_Text // default value == null;
Example m_Example; // default value == null;
public void Test() {
bool boolValue; // contains trash, must be initialized before using
int intValue; // contains trash, must be initialized before using
double doubleValue; // contains trash, must be initialized before using
string textValue; // reference to trash, must be initialized before using
Example example; // reference to trash, must be initialized before using
...
}
}