C#声明空字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16834245/
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-10 07:54:30  来源:igfitidea点击:

C# declare empty string array

c#arraysstring

提问by aquanat

I need to declare an empty string array and i'm using this code

我需要声明一个空字符串数组,我正在使用此代码

string[] arr = new String[0]();

But I get "method name expected" error.

但我收到“预期的方法名称”错误。

What's wrong?

怎么了?

采纳答案by Atish Dipongkor - MVP

Try this

尝试这个

string[] arr = new string[] {};

回答by Andrei

Your syntax is wrong:

你的语法错误:

string[] arr = new string[]{};

or

或者

string[] arr = new string[0];

回答by Rahul

If you must create an empty array you can do this:

如果您必须创建一个空数组,您可以这样做:

string[] arr = new string[0];

If you don't know about the size then You may also use List<string>as well like

如果你不知道的大小,然后你也可以使用List<string>,以及像

var valStrings = new List<string>();

// do stuff...

string[] arrStrings = valStrings.ToArray();

回答by Soner G?nül

Your syntax is invalid.

您的语法无效。

string[] arr = new string[5];

That will create arr, a referenced array of strings, where all elements of this array are null. (Since strings are reference types)

这将创建arr一个引用的字符串数组,其中该数组的所有元素都是null。(因为字符串是引用类型

This array contains the elements from arr[0]to arr[4]. The newoperator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to null.

此数组包含从arr[0]到的元素arr[4]。该new运算符用于创建数组并将数组元素初始化为其默认值。在这个例子中,所有的数组元素都被初始化为null

Single-Dimensional Arrays (C# Programming Guide)

Single-Dimensional Arrays (C# Programming Guide)

回答by CodeCaster

Those curly things are sometimes hard to remember, that's why there's excellent documentation:

那些卷曲的东西有时很难记住,这就是为什么有优秀的文档

// Declare a single-dimensional array  
int[] array1 = new int[5];

回答by Bharadwaj

You can try this

你可以试试这个

string[] arr = {};

回答by It'sNotALie.

Arrays' constructors are different. Here are some ways to make an empty string array:

数组的构造函数是不同的。以下是创建空字符串数组的一些方法:

var arr = new string[0];
var arr = new string[]{};
var arr = Enumerable.Empty<string>().ToArray()

(sorry, on mobile)

(对不起,在手机上)

回答by Brian

If you are using .net 4.6, they have some new syntax you can use:

如果您使用 .net 4.6,它们有一些您可以使用的新语法:

using System;  // To pick up definition of the Array class.

var myArray = Array.Empty<string>();

回答by Karthikeyan Gunasheker

The following should work fine.

以下应该可以正常工作。

string[] arr = new string[] {""};