下面的引用返回示例来自C#7.0中的新增功能:
public ref int Find(int number, int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == number)
{
return ref numbers[i]; // return the storage location, not the value
}
}
throw new IndexOutOfRangeException($"{nameof(number)} not found");
}
编译没有任何问题(正如您期望的那样,它是从Microsoft博客复制而来的)。
我已经写了这个:
private static ref int GetReference(string searchTerm)
{
var passwords = new Dictionary<string, int>
{
{"password", 1},
{"123456", 2},
{"12345678", 3},
{"1234", 4},
{"qwerty", 5},
{"12345", 6},
{"dragon", 7}
};
return ref passwords[searchTerm];
}
但是,这个不编译。它给出以下错误:
CS8156在此上下文中不能使用表达式,因为它可能不会被引用返回
为什么从数组返回却不能从集合返回呢?
答案在您发布的同一链接中:
您只能返回“可以安全返回”的引用:传递给您的引用和指向对象字段的引用。
您的示例都不满足。您正在函数内部创建列表(因此对象将超出范围,并且其指针将无效),并且它不指向对象的字段。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句