为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
慕桂英546537 2022-12-31 13:03:19
我开始学习 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 BoxBox* Box2 = new Box();   // Declare Box2 of type Box
查看完整描述

1 回答

?
眼眸繁星

TA贡献1873条经验 获得超9个赞

您的第二个示例声明了一个变量,但它将为空且无法访问:


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 null

try

{

    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 variable

b = new Box(); // initialize the variable


int 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 中的结构和类有何区别?


查看完整回答
反对 回复 2022-12-31
  • 1 回答
  • 0 关注
  • 99 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号