【问题标题】:Multidimentional array example in c# .netc# .net 中的多维数组示例
【发布时间】:2009-06-22 09:14:41
【问题描述】:

我对理解多维数组感到困惑。我有三个数据(strFname、strLname、strMname)。

我需要把这些数据放在一个多维数组中。可能有 n 行。但是对于每一行,我需要添加这三个数据。

【问题讨论】:

标签: c# multidimensional-array


【解决方案1】:

那可能是string[,]:

    string[,] data = new string[4, 3] {
        {"a","b","c"},
        {"d","e","f"},
        {"g","h","i"},
        {"j","k","l"}
    };

但是,我建议您创建一个具有预期属性的类型,并拥有该类型的 List<T> - 更容易理解:

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
}
...
List<Person> people = new List<Person>();
people.Add(new Person {FirstName = "Fred", ... });

【讨论】:

    【解决方案2】:

    我认为你不应该在这里使用多维数组 - 我认为你应该将三个值封装在一个类型中 - 像这样(假设我已经正确解释了名称):

    public sealed class Name
    {
        private readonly string firstName;
        private readonly string lastName;
        private readonly string middleName;
    
        // Consider changing the ordering here?
        public Name(string firstName, string lastName, string middleName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
            this.middleName = middleName;
        }
    
        public string FirstName
        {
            get { return firstName; }
        }
    
        public string LastName
        {
            get { return lastName; }
        }
    
        public string MiddleName
        {
            get { return middleName; }
        }
    }
    

    然后您可以使用List&lt;Name&gt;Name[],这两者都可以明确目的。

    (是的,现在这与 Marc 的回答基本相同,除了我的类型是不可变的 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-21
      • 2014-06-20
      • 2016-12-07
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多