简体   繁体   中英

Array reference in classes in C#

i have an array and want to create two classes that contains the reference of this array. When i change value of an element in array, i want to see the change in classes. The reason why i want to do that is i have a array of something and i have many classes that should contain or reach this array. How can i do that?

In C, i put the pointer of the array in existing structs and solve the problem but how can i do that in C#? There is no array pointer 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];

Thank you.

All arrays are reference types in C#, even if the element type of the array is a value type. So this will be fine:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM