在数组 setter / setter 中使用寻址索引
Using the adressed index in an array setter / setter
我想在数组的 getter 和 setter 中正确处理超出范围的索引(不是通过异常处理程序),就像这样(不起作用):
byte[] Board {
get {
if (index >= 0 && index < Board.Length)
return Board[index];
else
return 3;
}
set {
if (index >= 0 && index < Board.Length)
Board[index] = value;
}
}
所以,例如Board[1]
returns Board[1] 和 Board[-1]
returns 3.
的内容
执行此操作的正确方法是什么?
你不能用 setter 和 getter 做到这一点。
解决方法是创建一个名为 Array<T>
的数组包装器 class。添加类型为 T[]
的字段作为 "backing field"。然后实现 T[]
的所有成员,例如 Length
或 IEnumerable<T>
接口。例如,
class Array<T> {
T[] _array;
public int Length => _array.Length;
public Array(int length) {
_array = new T[length];
}
}
重要的部分来了,您现在可以将索引器添加到数组包装器中:
public T this[int index] {
get {
if (index >= 0 && index < _array.Length) {
return _array[index];
} else {
return 3;
}
}
set {
if (index >= 0 && index < _array.Length) {
_array[index] = value;
}
}
}
然后,您可以使用 Array<byte>
作为您的板的类型。
在 C# 属性中只能 get/set "themselves"。这意味着如果你有一个数组,你只能 get/set 数组本身,而不是单个值。但是,您可以创建外观和行为都符合您要求的方法,如下所示:
public byte getBoardValue(int index) {
if (index >= 0 && index < Board.Length)
return _board[index];
else
return 3;
}
public void setBoardValue(int index, byte value) {
if (index >= 0 && index < Board.Length)
_board[index] = value;
}
我想在数组的 getter 和 setter 中正确处理超出范围的索引(不是通过异常处理程序),就像这样(不起作用):
byte[] Board {
get {
if (index >= 0 && index < Board.Length)
return Board[index];
else
return 3;
}
set {
if (index >= 0 && index < Board.Length)
Board[index] = value;
}
}
所以,例如Board[1]
returns Board[1] 和 Board[-1]
returns 3.
执行此操作的正确方法是什么?
你不能用 setter 和 getter 做到这一点。
解决方法是创建一个名为 Array<T>
的数组包装器 class。添加类型为 T[]
的字段作为 "backing field"。然后实现 T[]
的所有成员,例如 Length
或 IEnumerable<T>
接口。例如,
class Array<T> {
T[] _array;
public int Length => _array.Length;
public Array(int length) {
_array = new T[length];
}
}
重要的部分来了,您现在可以将索引器添加到数组包装器中:
public T this[int index] {
get {
if (index >= 0 && index < _array.Length) {
return _array[index];
} else {
return 3;
}
}
set {
if (index >= 0 && index < _array.Length) {
_array[index] = value;
}
}
}
然后,您可以使用 Array<byte>
作为您的板的类型。
在 C# 属性中只能 get/set "themselves"。这意味着如果你有一个数组,你只能 get/set 数组本身,而不是单个值。但是,您可以创建外观和行为都符合您要求的方法,如下所示:
public byte getBoardValue(int index) {
if (index >= 0 && index < Board.Length)
return _board[index];
else
return 3;
}
public void setBoardValue(int index, byte value) {
if (index >= 0 && index < Board.Length)
_board[index] = value;
}