2

我有一个数组,想创建两个包含该数组引用的类。当我更改数组中元素的值时,我想查看类的变化。我想这样做的原因是我有一个数组,我有很多类应该包含或到达这个数组。我怎样才能做到这一点?

在 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];

谢谢你。

4

1 回答 1

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
于 2012-05-28T05:46:31.613 回答