【发布时间】:2020-06-30 17:47:20
【问题描述】:
我用索引器创建了一个类。
public class IntArray
{
protected int[] _thisArray = new int[20];
// --------------- ARRAY --------------- //
public int this[int index] { get => _thisArray[index]; }
}
现在我想通过引用访问索引器。 这是我尝试过的:
private void AccessWithReference()
{
var intArray = new IntArray();
SetByReference(ref intArray[0]);
}
private void SetByReference(ref int value) { value = 0; }
但是我得到一个错误。另一方面,如果我尝试直接访问数组ref _thisArray[0],一切都很好。
如何通过 ref 访问索引器?
【问题讨论】:
-
索引器不需要由您可以通过引用访问的任何内容(想想计算值)支持,这就是为什么这通常不起作用的原因。不过,
public ref int this[int index] { get => ref _thisArray[index]; }会的。 -
是的。我确定。感谢您的回答。