gpt4 book ai didi

c# - 没有语言语法 [] 实例化新数组

转载 作者:太空狗 更新时间:2023-10-30 00:43:32 25 4
gpt4 key购买 nike

在 C# 中,可以使用特殊的方括号语法 new int[3] 来实例化一个数组。 .这与您通过调用构造函数实例化的其他类型不同 new List<int>() .你能用普通语法创建数组吗?

我试过了 new System.Array<int>(3)但是它爆炸了

The non-generic type 'System.Array' cannot be used with type arguments

最佳答案

System.Array本身是抽象的,因此您将无法使用其构造函数实例化它。正如您的错误所证明的那样,它实际上也不是通用的;它只能通过 implementing generic collection interfaces at runtime 获取其类型(另见 this related answer ):

Important

In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools.

由于上述原因,System.Array类提供了一个名为 CreateInstance() 的便捷方法您可以改用它:

var array = Array.CreateInstance(typeof(int), 3);

Remarks

Unlike most classes, Array provides the CreateInstance method, instead of public constructors, to allow for late bound access.

不过,使用此方法时非常要小心,因为结果 array 不会在编译时被强类型化!如果你希望它是强类型的,你必须在创建它之后转换它(不,仅仅声明 int[] array 是不够的):

var array = (int[]) Array.CreateInstance(typeof(int), 3);

关于c# - 没有语言语法 [] 实例化新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10837744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com