C# 中类中的数组引用
本文关键字:引用 数组 | 更新日期: 2023-09-27 18:35:27
我有一个数组,想要创建两个包含此数组引用的类。当我更改数组中元素的值时,我想查看类的变化。我想这样做的原因是我有一个数组,我有很多类应该包含或访问这个数组。我该怎么做?
在 C 中,我将数组的指针放在现有结构中并解决问题,但我如何在 C# 中做到这一点?没有数组指针 afaik。
int CommonArray[2] = {1, 2};
struct
{
int a;
int *CommonArray;
}S1;
struct
{
int b;
int *CommonArray;
}S2;
S1.CommonArray = &CommonArray[0];
S2.CommonArray = &CommonArray[0];
谢谢。
所有数组都是 C# 中的引用类型,即使数组的元素类型是值类型也是如此。所以这会很好:
public class Foo {
private readonly int[] array;
public Foo(int[] array) {
this.array = array;
}
// Code which uses the array
}
// This is just a copy of Foo. You could also demonstrate this by
// creating two separate instances of Foo which happen to refer to the same array
public class Bar {
private readonly int[] array;
public Bar(int[] array) {
this.array = array;
}
// Code which uses the array
}
...
int[] array = { 10, 20 };
Foo foo = new Foo(array);
Bar bar = new Bar(array);
// Any changes to the contents of array will be "seen" via the array
// references in foo and bar