使用 new 和不使用 new 创建对象

我开始学习 C#,我发现有两种不同的方法来创建对象。首先是这样的:


 Box Box1 = new Box();   // Declare Box1 of type Box

 Box Box2 = new Box();   // Declare Box2 of type Box

其他是这样的:


 Box Box1 ;   // Declare Box1 of type Box

 Box Box2 ;   // Declare Box2 of type Box

两种方法都有效,有什么区别?C++指针有类似的东西吗?


Box* Box1 = new Box();   // Declare Box1 of type Box

Box* Box2 = new Box();   // Declare Box2 of type Box


慕桂英546537
浏览 100回答 1
1回答

眼眸繁星

您的第二个示例声明了一个变量,但它将为空且无法访问:Box b;int id = b.Id; // Compiler will tell you that you're trying to use a unassigned local variable 我们可以通过用 null 初始化来欺骗编译器:Box b = null; // initialize variable with nulltry{    int id = b.Id; // Compiler won't notice that this is empty. An exception will be trown}catch (NullReferenceException ex){    Console.WriteLine(ex);}我们现在看到,我们必须初始化变量才能访问它:Box b; // declare an empty variableb = new Box(); // initialize the variableint id = b.Id; // now we're allowed to use it.声明和初始化的简短版本是您的第一个示例:Box b = new Box();这是我用于示例的示例类:public class Box{    public int Id { get; set; }}也许您确实注意到Id我们Box没有被初始化。这不是必需的(但大多数时候您应该这样做),因为它是值类型 ( struct) 而不是引用类型 ( class)。如果您想了解更多信息,请查看以下问题:.NET 中的结构和类有何区别?
打开App,查看更多内容
随时随地看视频慕课网APP