繁体   English   中英

C#中的类中的数组引用

[英]Array reference in classes in C#

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

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

谢谢。

即使数组的元素类型是值类型,所有数组也是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

暂无
暂无

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

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