以下通过引用返回的示例来自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");
}
Run Code Online (Sandbox Code Playgroud)
编译没有任何问题(正如你所期望的那样,它是从微软博客中复制的).
我写过这个:
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];
} …Run Code Online (Sandbox Code Playgroud)