创建未定义长度的 c# 对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1022885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:43:35  来源:igfitidea点击:

Create c# object array of undefined length?

c#arrays

提问by Lyndal

I would like to create an object array in C# of undefined length and then populate the array in a loop like so...

我想在 C# 中创建一个未定义长度的对象数组,然后像这样在循环中填充数组......

    string[] splitWords = message.Split(new Char[] { ' ' });

    Word[] words = new Word[];
    int wordcount = 0;
    foreach (string word in splitWords)
    {
        if (word == "") continue;
        words[wordcount] = new Word(word);
        wordcount++;
    }

However, I get the error... "Array creation must have array size or array initializer"

但是,我收到错误...“数组创建必须具有数组大小或数组初始值设定项”

I'm doing a lot more logic in the foreach loop that I've left out for brevity.

为了简洁起见,我在 foreach 循环中做了更多的逻辑。

采纳答案by jasonh

What you want to do is create:

您要做的是创建:

List<Word> words = new List<Word>();

and then:

进而:

words.Add(new Word(word));

And finally when the loop is done if you need an array:

最后当循环完成时,如果你需要一个数组:

words.ToArray();

回答by statenjason

You can't create an array of undefined length. This is where you'd use a generic List.

您不能创建未定义长度的数组。这是您使用通用列表的地方。

List<Word> words = new List<Word>();

回答by JaredPar

If you're using C# 3.5, you can just do the following.

如果您使用的是 C# 3.5,则只需执行以下操作。

var words = message
  .Split(new char[]{' '}) 
  .Where(x => x != "")
  .Select(x => new Word(x))
  .ToArray();

回答by Lyndal

I solved it by using an ArrayList and then casting it to the object array after iterating...

我通过使用 ArrayList 解决了它,然后在迭代后将其转换为对象数组...

    string[] splitWords = message.Split(new Char[] {' '});
    ArrayList wordList = new ArrayList();
    int wordcount = 0;
    foreach (string word in splitWords)
{
        if (word == "") continue;
        Word newWord = new Word(word);
        wordList.Add(newWord);
        wordcount++;
}
    Word[] words = (Word[])wordList.ToArray(typeof(Word)); 

I've heard the whole "create question/answer just to document it for others" is acceptable. Plus I'd like to hear if there are better suggestions. Thanks.

我听说整个“创建问题/答案只是为了为他人记录”是可以接受的。另外,我想听听是否有更好的建议。谢谢。

回答by David.Chu.ca

Actually you may use list to populate your words first and then convert it easily to array like this:

实际上,您可以先使用 list 填充单词,然后将其轻松转换为数组,如下所示:

string[] splitWords = message.Split(new Char[] { ' ' });

List<Word> words = new List<Word>();
int wordcount = 0;
foreach (string word in splitWords)
{
    if (word == "") continue;
    words.add(new Word(word));
    //wordcount++;
}

wordcount = words.count;
return words.ToArray();

回答by Talljoe

A friendly note, you can pass option to split to ignore empty entries. Assuming no other logic to prune out entries you can preinitialize your array like so:

友情提示,您可以通过选项 split 来忽略空条目。假设没有其他逻辑来修剪条目,您可以像这样预初始化数组:

string[] splitWords = message.Split(new Char[] {' '},
  StringSplitOptions.RemoveEmptyEntries);
Word[] words = new Word[splitWords.Length];

回答by Aaaaa

I'm wondering why can't we just use a string variable (say x), initialize it and retrieve comma separated data in it and later use string[]variable (say y[]) and initialize it equal to x.Split(',')without having to initialize a blank array like follows:

我想知道为什么我们不能只使用字符串变量(比如x),初始化它并检索其中的逗号分隔数据,然后使用string[]变量(比如y[])并将其初始化为等于x.Split(',')而不必初始化一个空数组,如下所示:

string x = string.Empty;
string msg = "hi,how,r,u,xyz";

void Page_Load(object sender, EventArgs e)
     x = msg;
     string[] y = msg.Split(',');

I think this should work as needed but I didn't try running this so I am not sure. If someone thinks that my solution is wrong, please correct me.

我认为这应该根据需要工作,但我没有尝试运行它,所以我不确定。如果有人认为我的解决方案是错误的,请纠正我。