C# 中创建对象数组

以前一直没有在C#中创建过对象数组,今天写了个小练习,结果用到对象数组的时候不会用了。

 

在C#中创建对象数组不像C++。

 

代码:

 

 Student[] student=new Student[5];


 

这里在创建对象数组的时候没有用括号指定参数,不像创建单个对象那样

创建单个对象的代码:

Student student=new Student();


同时如果在创建对象数组的时候前面的数组维数中括号不能指定维数,如果指定维数则编译出错:

Student[5] student=new Student[5]; //这里是编译不过去的。

 

请注意, 在创建一个对象数组以后,没有生成任何对象,而是简单一个对对象的引用的数组,如果这个时候要使用对象,会出现空指针引用。在具体的使用数组中每一个引用的时候,还需要用new 创建对象.

 Student[] student = new Student[5];
            student[0] = new Student();
            student[0].Age = 12;
            student[1] = new Student();
            student[1].Age = 13;
            student[2] = new Student();
            student[2].Age = 74;
            student[3] = new Student();
            student[3].Age = 34;
            student[4] = new Student();
            student[4].Age = 32;


然后才可以使用对象数组。这里和C++是不一样的。也就是说,每一个数组元素都要单独的初始化。

  • 10
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值