2

配列があり、この配列の参照を含む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 に答える