gpt4 book ai didi

c# - 数组的结构是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 23:18:54 24 4
gpt4 key购买 nike

我知道 C# 中的 Array 是一个对象但是一些代码实际上让我感到困惑

int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers)
Console.WriteLine(i);

访问任意对象的任意属性int value= object.property;

在这个循环中,它有点访问属性,但是如何访问呢?这里的属性(property)本身是什么?他们是如何组织的?

最佳答案

数据是如何存储的

基本上,数组是一团数据。整数是 32 位有符号整数的值类型。

C# 中的标识符要么是指向对象的指针,要么是实际值。在引用类型的情况下,它们是真正的指针,在值类型(例如 int、float 等)的情况下,它们是实际的数据。 int是值类型,int[] (数组到整数)是引用类型。

它这样工作的原因基本上是“效率”:为值类型复制 4 个字节或 8 个字节的开销非常小,而复制整个数组的开销可能非常大。

如果你有一个包含 N 个整数的数组,它只不过是一个 N*4 字节的 blob,变量指向第一个元素。 blob 中的每个元素都没有名称。

例如:

int[] foo = new int[10]; // allocates 40 bytes, naming the whole thing 'foo'
int f = foo[2]; // allocates variable 'f', copies the value of 'foo[2]' into 'f'.

访问数据

至于foreach...在C#中,所有的集合都实现了一个名为IEnumerable<T>的接口(interface).如果您使用它,在这种情况下,编译器会注意到它是一个整数数组,并且会遍历所有元素。换句话说:

foreach (int f in foo) // copy value foo[0] into f, then foo[1] into f, etc
{
// code
}

是(在数组的情况下!)完全相同的东西:

for (int i=0; i<foo.Length; ++i)
{
int f = foo[i];
// code
}

请注意,我在这里明确地放置了“在数组的情况下”。数组是 C# 编译器的特例。如果您不使用数组(例如使用 ListDictionary 或更复杂的东西),它的工作方式会有所不同,即使用 EnumeratorIDisposable .请注意,这只是一个编译器优化,数组完全能够处理 IEnumerable .

对于那些感兴趣的人,基本上它会为非数组和非字符串生成这个:

var e = myEnumerable.GetEnumerator();
try
{
while (e.MoveNext())
{
var f = e.Current;
// code
}
}
finally
{
IDisposable d = e as IDisposable;
if (d != null)
{
d.Dispose();
}
}

如果你想要一个名字

您可能需要一个 Dictionary .

关于c# - 数组的结构是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36133122/

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