【问题标题】:Can we initialize an array if we use it with a structure object? | C#如果我们将它与结构对象一起使用,我们可以初始化一个数组吗? | C#
【发布时间】:2016-07-18 04:50:53
【问题描述】:

我们知道一个简单的数组可以像这样初始化,例如int [] TestArray = {1,2,3,4},但是如果我们使用一个带有结构对象的数组并且我们想要初始化它呢?

我知道我们可以像这样访问结构对象数组,例如,

假设 struct Automobile 是我们的结构体,其中有 public int yearpublic string model 等字段,我们创建了一个数组结构体对象,例如 Automobile [] Car = new Automobile();,这样我们就可以访问结构体数组对象的元素,并且如果我们将它与结构字段一起使用,则给它一个值,例如Car[2].year = "2016",然后可以将其显示在例如,

MessageBox.Show(Car[2].year.ToString()); 

但是,如果我们希望我们的结构数组对象具有初始值,就像我们在开始时所写的正常数组初始化中所拥有的那样?

【问题讨论】:

    标签: c# arrays object


    【解决方案1】:

    试试

    var auto = new[]
            {
                new Automobile {year = 1984, model = "charger"},
                new Automobile {year = 1985, model = "challenger"},
                new Automobile {year = 1984, model = "hemicuda"}
            };
    

    var auto = new[]Automobile[] auto = new Automobile[] 的简写形式,如果您觉得更舒服,可以使用它。

    【讨论】:

      【解决方案2】:

      让结构定义如下:

      public struct Automobile
      {
          public int Year { get; set; }
          public string model { get; set; }
      }
      

      然后你可以创建这个结构变量的数组,如下所示:

      Automobile[] AutomobileList = new Automobile[] { 
                                     new Automobile() {Year=2015,model="Some model1" },
                                     new Automobile() {Year=2014,model="Some model2" },
                                     new Automobile() {Year=2013,model="Some model3" }};
      

      你也可以用类似的方式定义一个列表;

      List<Automobile> AutomobileList = new List<Automobile>() { 
                                         new Automobile() {Year=2015,model="Some model1" },
                                         new Automobile() {Year=2014,model="Some model2" },
                                         new Automobile() {Year=2013,model="Some model3" }};
      

      【讨论】:

      • 什么是get; set 以及为什么在没有它的情况下也使用它?您能与我们分享您的知识吗?
      • @GhostRider - 你以前没见过get; set;吗?
      • 那是用来定义Properties的,你可以用这个Thread来了解Difference between Variables and properties
      猜你喜欢
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 2012-04-25
      • 2022-01-04
      • 2012-07-13
      • 1970-01-01
      • 2021-06-02
      • 2019-06-17
      相关资源
      最近更新 更多