[英]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.