C#中数组的初始化

迪米特里斯·普拉蒂斯

我想问一些相当基本的问题(我认为)似乎我无法回答的答案。在下面的代码中,我试图加载一个包含两列 ( string Name, int Score)的 csv 文件 (; 分隔) 的数组为简单起见,我已经注释掉了我想用来将此文件传输到数组的循环,而我只是加载了第二个元素。出于某种原因,除非我使用 ( scoreobj[1] = new HighScore();),否则我会得到一个null参考。为什么我需要这样做?一开始我不是已经初始化了scoreobj[]对象吗?

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
   public class HighScore
   {
      public string Name { get; set; }
      public int Score { get; set; }

      public static void LoadHighScores(string filename)
      {
         string[] scoredata = File.ReadAllLines("C:/Users/User/Desktop/Test.csv");
         HighScore[] scoreobj = new HighScore[scoredata.Length];
         scoreobj[1] = new HighScore();
         scoreobj[1].Name = scoredata[1].Split(';')[0];

         //for (int index = 0; index < scoredata.Length; index++)
         //{
         //   scoreobj[index].Name = scoredata[index].Split(',')[0];
         //   scoreobj[index].Score = Convert.ToInt32(scoredata[index].Split(';')[1]);

         //}

         Console.WriteLine(scoreobj[1].Name);
      }
   }
}
HimBromBeere

因为仅仅声明一个特定大小的索引不会创建任何类型的元素HighScore相反,您只需保留一些内存。换句话说:仅仅因为你有一个袋子并没有在里面放任何土豆。你必须自己去市场把土豆放进你的包里。

您甚至可以创建派生类的实例并将其放入完全相同的数组中。在这种情况下,编译器如何知道您要实例化哪个类?

class Foo { ... }
class Bar { ... }

var array = new Foo[3]; // how would anyone know if you want three Foo-instances or 3 Bar-instances? or a mix?

编译器不知道您要实例化哪种类型,因此不会创建这些实例。所以你必须自己创建实例。

但即使没有派生类,您的构造函数也可能有参数,编译器无法猜测:

class HighScore
{
    public HighScore(string name, int score) { ... }
}

var array = new HighScore[3]; // how to set the parameters for the instances???

这就是为什么你的对象不包含实例,而只包含类型默认值,这是null用于引用类型。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章