如何在C#中初始化一个空数组?

在C#中,不指定大小创建空数组通常没有意义,因为数组的本质涉及大小。然而,可以创建一个大小为0的空数组。例如,通过`string[] arr = new string[0];`或使用`.Empty`属性,如`Array.Empty<string>()`。在某些情况下,如传递参数,初始化一个空数组可能是有用的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:How do I initialize an empty array in C#?

Is it possible to create an empty array without specifying the size? 是否可以在不指定大小的情况下创建一个空数组?

For example, I created: 例如,我创建了:

String[] a = new String[5];

Can we create the above string array without the size? 我们可以创建没有大小的上述字符串数组吗?


#1楼

参考:https://stackoom.com/question/acKQ/如何在C-中初始化一个空数组


#2楼

There is not much point in declaring an array without size. 声明没有大小的数组没有多大意义。 An array is about size . 一个数组大约是size When you declare an array of specific size, you specify the fixed number of slots available in a collection that can hold things, and accordingly memory is allocated. 声明特定大小的数组时,请在集合中指定可容纳事物的固定可用插槽数,并相应地分配内存。 To add something to it, you will need to anyway reinitialize the existing array (even if you're resizing the array, see this thread ). 要向其中添加一些内容,无论如何您都需要重新初始化现有的数组(即使您要调整数组的大小,也请参见此线程 )。 One of the rare cases where you would want to initialise an empty array would be to pass array as an argument. 您想初始化一个空数组的罕见情况之一是将数组作为参数传递。

If you want to define a collection when you do not know what size it could be of possibly, array is not your choice, but something like a List<T> or similar. 如果要在不知道集合的大小的情况下定义集合,则数组不是您的选择,而是类似List<T>或类似的东西。

That said, the only way to declare an array without specifying size is to have an empty array of size 0 . 也就是说,声明一个不指定大小的数组的唯一方法是拥有一个大小为0的空数组。 hemant and Alex Dn provides two ways. hemantAlex Dn提供了两种方法。 Another simpler alternative is to just : 另一个更简单的选择是

string[] a = { };

[ The elements inside the bracket should be implicitly convertible to type defined, for instance, string[] a = { "a", "b" }; [ 括号内的元素应隐式转换为定义的类型,例如string[] a = { "a", "b" }; ] ]

Or yet another: 还是另一个:

var a = Enumerable.Empty<string>().ToArray();

Here is a more declarative way : 这是一种更具声明性的方式

public static class Array<T>
{
    public static T[] Empty()
    {
        return Empty(0);
    }

    public static T[] Empty(int size)
    {
        return new T[size];
    }
}

Now you can call: 现在您可以致电:

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

//or

var a = Array<string>.Empty(5);

#3楼

You can do: 你可以做:

string[] a = { String.Empty };

Note: OP meant not having to specify a size, not make an array sizeless 注:OP意味着不必指定大小,而不是让一个数组没有尺寸


#4楼

In .Net 4.6 the preferred way is to use a new method, Array.Empty : 在.Net 4.6中,首选方法是使用新方法Array.Empty

String[] a = Array.Empty<string>();

The implementation is succinct, using how static members in generic classes behave in .Net : 使用通用类中的静态成员在.Net中的行为, 实现是简洁的:

public static T[] Empty<T>()
{
    return EmptyArray<T>.Value;
}

// Useful in number of places that return an empty byte array to avoid
// unnecessary memory allocation.
internal static class EmptyArray<T>
{
    public static readonly T[] Value = new T[0];
}

(code contract related code removed for clarity) (为清楚起见,删除了与代码合同相关的代码)

See also: 也可以看看:


#5楼

Combining @nawfal & @Kobi suggestions: 结合@nawfal和@Kobi建议:

namespace Extensions
{
    /// <summary> Useful in number of places that return an empty byte array to avoid unnecessary memory allocation. </summary>
    public static class Array<T>
    {
        public static readonly T[] Empty = new T[0];
    }
}

Usage example: 用法示例:

Array<string>.Empty

UPDATE 2019-05-14 更新2019-05-14

(credits to @Jaider ty) (归功于@Jaider ty)

Better use .Net API: 更好地使用.Net API:

public static T[] Empty<T> ();

https://docs.microsoft.com/en-us/dotnet/api/system.array.empty?view=netframework-4.8 https://docs.microsoft.com/zh-cn/dotnet/api/system.array.empty?view=netframework-4.8

Applies to: 适用于:

.NET Core: 3.0 Preview 5 2.2 2.1 2.0 1.1 1.0 .NET Core:3.0预览版5 2.2 2.1 2.0 1.1 1.0

.NET Framework: 4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 .NET Framework:4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6

.NET Standard: 2.1 Preview 2.0 1.6 1.5 1.4 1.3 .NET标准:2.1预览版2.0 1.6 1.5 1.4 1.3

... ...

HTH 高温超导


#6楼

简洁大方!

string[] array = {}
### C# 中清数组的方法或初始化C# 中,清数组或将其初始化可以通过多种方式实现。以下是几种常见的方法: #### 方法一:使用 `Array.Clear` 方法 `Array.Clear` 是一种简单且高效的方式,用于将数组中的所有元素设置为默认值(例如,对于整数数组,默认值为 0)。这种方法不会改变数组的长度,仅修改其内容。 ```csharp int[] array = { 1, 2, 3, 4, 5 }; Array.Clear(array, 0, array.Length); // 将数组的所有元素设置为默认值 ``` 上述代码中,`Array.Clear` 将数组 `array` 的所有元素从索引 0 开始到整个长度范围内设置为默认值[^1]。 #### 方法二:重新分配数组 如果需要完全清数组并将其重新初始化一个新的数组,可以使用以下方法: ```csharp int[] array = { 1, 2, 3, 4, 5 }; array = new int[0]; // 创建一个长度为 0 的新数组 ``` 通过这种方式,原数组被替换为一个新的数组,其长度为 0。这相当于清数组[^2]。 #### 方法三:使用循环手动设置默认值 对于某些特定需求,可能需要手动遍历数组并将其每个元素设置为默认值: ```csharp int[] array = { 1, 2, 3, 4, 5 }; for (int i = 0; i < array.Length; i++) { array[i] = default(int); // 将每个元素设置为默认值 } ``` 此方法适用于需要自定义逻辑的情况,但通常不如 `Array.Clear` 高效[^3]。 #### 方法四:使用 LINQ 进行操作 虽然 LINQ 主要用于查询集合,但也可以结合其他方法来清数组。例如,创建一个数组并赋值给原数组: ```csharp using System.Linq; int[] array = { 1, 2, 3, 4, 5 }; array = Enumerable.Empty<int>().ToArray(); // 创建一个数组 ``` 这种方法生成了一个数组并将其赋值给原数组变量[^4]。 ### 注意事项 - 如果需要保留数组的引用但清其内容,应使用 `Array.Clear` 或循环方法。 - 如果不需要保留数组的引用,则可以直接创建一个新的数组。 - 清数组时需注意其类型和用途,以选择最适合的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值