在C#中声明不知道其大小的2D数组 [英] Declaring a 2D array without knowing its size in C#

查看:72
本文介绍了在C#中声明不知道其大小的2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用2-D数组,但我无法提前知道它的大小.所以我的问题是:如何声明它?然后如何向其中添加值?

I would like to use a 2-D array but I can't know its size in advance. So my question is: how to declare it? And then how to add values into it?

String[,] tabConfig = new String[?, 4];
foreach(blabla with i)
{
    tabConfig[i, 0] = a;
    tabConfig[i, 1] = b;
    tabConfig[i, 2] = c;
    tabConfig[i, 3] = d;
}

我知道我也可以使用列表,但我对此并不十分熟悉.

I know I can also use a list but I am not very familiar with it.

谢谢!

振作起来!在乔恩·斯凯特(Jon Skeet)的帮助下,这是我真正的代码!

Brace yourselves! Here come my true code with Jon Skeet's help!

List<string[]> tabConfig = new List<string[]>();
String[] temp = new String[4];//The array that will be inside the List
int line = 0, column = 0;

foreach (XmlNode e in doc.DocumentElement.ChildNodes)
{
    if (e.Attributes["Server"].Value == choice)
    {
        temp[0] = e.Attributes["Serveur"].Value;//Here is value 'a'

        column = 1;
        foreach (XmlNode i in e.ChildNodes)
        {
            temp[colonne] = i.InnerText;//Here are values 'b', 'c' and 'd'
            column++;
        }
        tabConfig.Add(temp);//Put a new line into the List
        line++;
    }
}

并称之为:

foreach(string[] array in tabConfig)
    foreach(String txt in array)
        Console.WriteLine(txt);

推荐答案

所以我的问题是:如何声明它?

So my question is: how to declare it?

不能..NET中的所有数组都是固定大小的:您无法在不知道大小的情况下创建数组实例.

You can't. All arrays in .NET are fixed size: you can't create an array instance without knowing the size.

在我看来,您应该有一个 List< T> -并且我实际上将创建一个类来保存这四个属性,而不仅仅是使用数组的四个元素.您可以使用数组列表:

It looks to me like you should have a List<T> - and I'd actually create a class to hold the four properties, rather than just using four elements of an array, probably. You could use a list of arrays:

List<string[]> tabConfig = new List<string[]>();
foreach (...)
{
    tabConfig.Add(new string[] { a, b, c, d });
}

...但是您需要了解这四个元素在排序等方面的含义,这可能会使其余代码难以理解.

... but then you need to know what those four elements mean in terms of ordering etc, which is likely to make the rest of your code harder to understand.

这篇关于在C#中声明不知道其大小的2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆