C#中类的数组引用

san*_*p22 2 c# arrays class

我有一个数组,并希望创建两个包含此数组的引用的类.当我更改数组中元素的值时,我想看到类中的更改.我想要这样做的原因是我有一些东西,我有很多类应该包含或达到这个数组.我怎样才能做到这一点?

在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];
Run Code Online (Sandbox Code Playgroud)

谢谢.

Jon*_*eet 5

所有数组都是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
Run Code Online (Sandbox Code Playgroud)