简体   繁体   English

C#中的类中的数组引用

[英]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#? 在C语言中,我将数组的指针放在现有的结构中并解决了问题,但是如何在C#中做到这一点呢? There is no array pointer afaik. 没有数组指针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. 即使数组的元素类型是值类型,所有数组也是C#中的引用类型。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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