相关疑难解决方法(0)

为什么不通过ref返回集合元素?

以下通过引用返回的示例来自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)

.net c# c#-7.0

21
推荐指数
2
解决办法
1604
查看次数

标签 统计

.net ×1

c# ×1

c#-7.0 ×1