【问题标题】:How can I access an indexer by reference如何通过引用访问索引器
【发布时间】: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]; } 会的。
  • 是的。我确定。感谢您的回答。

标签: c# arrays ref


【解决方案1】:

Microsoft docs 表示“索引器值未分类为变量;因此,您不能将索引器值作为 ref 或 out 参数传递。”
您可以使用临时变量来完成这项工作,如下所示:

private void AccessWithReference()
{
   IntArray intArray = new IntArray();
   int a = intArray[0];
   SetByReference(ref a);
}

索引器已经是 reference 类型

【讨论】:

  • 感谢您的回答。使用您的解决方案,我仍然需要在堆栈中添加一些内容并重新分配它。我知道我的示例使用 int 使情况变得简单,但实际上我有一个非常大的结构和一个长数组。也许我可以尝试使用 ref 返回。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 2015-12-14
  • 2010-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多