【问题标题】:why "return ref a[0]" doesn't change the original array?为什么“return ref a[0]”不会改变原始数组?
【发布时间】:2021-10-17 17:58:09
【问题描述】:

我打算在数组中返回一个值的引用(并对其进行操作),但是,当我在 method() 中传递数组时,结果不是我想要的。

而且我也很好奇我不能使用DEBUG监视器查询&amethod()堆栈中的地址。

任何人都可以帮助我正确使用return ref吗?

static void Main(string[] args)
{

    int?[] s = new int?[5] { 1, 2, 3, 4, 5 };
    var q = method(ref s);
    q = 999;
    Console.WriteLine("s0 is " + s[0].ToString());
}

static ref int? method(ref int?[] a)
{
    a[1] = 888;
    return ref a[0];
}

【问题讨论】:

标签: c# function reference method-call return-by-reference


【解决方案1】:

这是因为q 不是本地引用。它只是一个常规变量。您也没有在方法调用之前说ref,所以这只是一个常规的按值赋值。由于这些原因,q 不是a[0] 的别名。

documentation 给出了一个类似的例子:

假设GetContactInformation 方法被声明为ref return

public ref Person GetContactInformation(string fname, string lname)

按值赋值读取变量的值并将其分配给新变量:

Person p = contacts.GetContactInformation("Brandie", "Best");

前面的赋值将p 声明为一个局部变量。它的初始值是通过读取GetContactInformation 返回的值复制而来的。将来对p 的任何赋值都不会改变GetContactInformation 返回的变量的值。变量p 不再是返回变量的别名。

要解决此问题,您可以在 var 之前添加 ref 以使 q 成为本地引用,并在调用之前添加 ref 以使其成为按引用分配:

ref var q = ref method(ref s);

【讨论】:

  • 非常感谢您在官方文档的关键部分下划线!
猜你喜欢
  • 1970-01-01
  • 2019-07-27
  • 2015-11-22
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
  • 2019-10-14
  • 2016-06-24
相关资源
最近更新 更多