c# - 为什么按 ref 返回对集合元素不起作用?

标签 c# .net c#-7.0

下面引用返回的例子来自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 时才有效是一个领域。

但是,您正在使用 refDictionary<,> 上的索引属性,它根本不是 ref 的受支持表达式开始(即,即使在 C# 7 之前,您也不能将 ref passwords[searchTerm] 作为参数传递),更不用说通过 ref 返回了。

关于c# - 为什么按 ref 返回对集合元素不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43576471/

相关文章:

c# - 传递给静态方法的实例引用参数会被垃圾收集吗?

c# - C#重构问题

c# - 无法加载文件或程序集 'System.ValueTuple'

c# - 根据登录凭证隐藏/显示菜单项

c# - 如何防止 MyISAM 大表崩溃

c# - 如何使用 C# 在 Unity 中截取我的桌面应用程序的当前 View 的屏幕截图?

c# - 接收字符串作为内存流并进行编码后,将添加更多字符

c# - 在 C# 中使用 RTMP 或 RTSP 协议(protocol)

C#7 : Underscore ( _ ) & Star ( * ) in Out variable

C# 7.0 语言功能在 .Net 4.x 上出现编译错误