【问题标题】:Cannot use Classes on this ref ClassName (byRef) method Feature C# 7.2无法在此 ref ClassName (byRef) 方法上使用类功能 C# 7.2
【发布时间】:2019-04-26 02:16:00
【问题描述】:

我正在测试新的闪亮的 C# 7.1/7.2/7.3 功能,当我尝试 this ref 类时,它不工作,同时 this ref int 工作,你们知道如何制作它使用类?

代码示例:

    public static bool Works(this ref int i)
    {
        return i == 0;
    }

    public static bool DontWorks(this ref Test i)
    {
        return i.A == 0;
    }

    public class Test
    {
        public int A { get; set; }
    }

很抱歉标题有点糟糕,但我不知道如何使它变得更好,如果您愿意,请随时给我建议或编辑。

感谢您的宝贵时间,祝您有美好的一天。

【问题讨论】:

  • 请将代码粘贴到您的问题中,而不是使用屏幕截图。它可以帮助人们复制和粘贴您的代码以自己进行测试。
  • 扩展功能不需要ref
  • 你为什么认为你需要ref?没有它,您的代码也能正常工作。
  • @GabrielLuci 编辑问题谢谢。
  • this ref 仅适用于值类型。

标签: c# c#-7.2


【解决方案1】:

引用扩展方法只允许用于已知为结构的类型。这是故意的。这背后的原因可以在feature proposal document找到。

此外,常规类类型是引用类型。传递reference type as a parameter 不会复制对象,这与with value type parameters 不同。

【讨论】:

  • 感谢您向我解释并提供要阅读的材料,阅读您提供给我的链接学到了很多东西。
猜你喜欢
  • 2018-03-18
  • 2019-12-23
  • 2018-06-13
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多