C#中类的数组引用

时间:2012-05-28 05:43:31

标签: 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];

谢谢。

1 个答案:

答案 0 :(得分: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