C#:未实例化对象的默认值是什么?
我有一个关于c#中默认值的快速问题 未实例化时,对象的默认值是多少 以下是一个例子:C#:未实例化对象的默认值是什么?,c#,class,oop,C#,Class,Oop,我有一个关于c#中默认值的快速问题 未实例化时,对象的默认值是多少 以下是一个例子: public class Example { public Example() { Console.WriteLine("Content!"); } } public class MainClass { // obj = ??? Example obj; } 规则很简单 包含的局部变量根本没有初始化,因此包含垃圾 局部变量不会自动初始化,因此没有 默认值 字段由其默认值(零)初始化:
public class Example
{
public Example() { Console.WriteLine("Content!"); }
}
public class MainClass
{
// obj = ???
Example obj;
}
规则很简单
- 包含的局部变量根本没有初始化,因此包含垃圾
- 字段由其默认值(零)初始化:
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
...
}
}
你已经准备好了这个例子。为什么不做一个测试?为什么你在这里问而不是使用谷歌?
c#默认值的第一个谷歌结果
:您没有“未实例化对象”。您有一个未初始化的变量。public static T GetDefault(T value),其中T:class=>default(T);对象的默认值始终为空此问题是由无法再复制的问题或简单的印刷错误引起的。虽然类似的问题可能在这里的主题,这是一个解决的方式不太可能帮助未来的读者。这通常可以通过在发布前确定并仔细检查重现问题所需的最短程序来避免。