【问题标题】:Why can't I ref return a static readonly field?为什么我不能 ref 返回静态只读字段?
【发布时间】:2017-12-08 10:08:56
【问题描述】:

以下代码无法使用 C# 7.0 / Visual Studio 2017.2 编译:

class C {
    private static readonly int s = 5;
    public static ref int Data => ref s;
}

是否存在不允许对静态只读字段进行引用的技术原因,或者这只是缺少的功能?

错误信息说:

CS8162:静态只读字段无法通过引用返回。

【问题讨论】:

标签: c# return ref c#-7.0


【解决方案1】:

因为它是readonly。

ref的意义在于允许被引用的变量被改变,这会违反readonly。

【讨论】:

  • 好吧,我的理解有误。我认为ref 的重点是防止复制值类型(结构)。
  • @ventiseis:这是ref 的另一个目的。但是由于没有ref readonly,所以不能将两个目的分开。
【解决方案2】:

您还不能返回对只读字段的引用,因为 ref 返回是可变的。但是,ref readonly 功能计划用于 C# 的未来版本 (currently pencilled in for C# 7.2, but that may change)。

此功能可能会解决返回对只读字段的引用的能力,以及允许将ref 参数也标记为只读,以保证所引用的值不会被该方法修改。

【讨论】:

    【解决方案3】:

    这在 C# 7.2 中现在是可能的。

    class C {
        private static readonly int s = 5;
        public static ref readonly int Data => ref s;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 2018-06-30
      • 2018-03-28
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多