下面引用返回的例子来自What’s New in 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 An expression cannot be used in this context because it may not be returned by reference
为什么从数组返回有效,而从集合返回却无效?
最佳答案
在 C# 中,ref
适用于:
- 变量(局部或参数)
- 领域
- 阵列位置
ref
不适用于:
- 属性
- 事件
- C# 7 中的局部变量通过 ref 返回
请注意,对于字段和数组位置,访问数组的方式并不重要。即 return ref numbers[i];
不坚持 numbers
, 但它指向的数组。完全不像return ref numbers;
,只有在 numbers
时才有效是一个领域。
但是,您正在使用 ref
在 Dictionary<,>
上的索引属性,它根本不是 ref
的受支持表达式开始(即,即使在 C# 7 之前,您也不能将 ref passwords[searchTerm]
作为参数传递),更不用说通过 ref 返回了。
关于c# - 为什么按 ref 返回对集合元素不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43576471/