首页 > 解决方案 > C# 记录 ToString() 导致堆栈溢出并停止调试会话并出现一个奇怪的错误

问题描述

我编写了一个单元测试并使用新的 C# 记录来存储一些测试所需的数据。单元测试运行良好,但是当我设置断点并将鼠标移到记录变量名称上时,调试会话结束并且我收到了一个看起来很奇怪的错误消息。

为了向 Microsoft 报告问题,我编写了一个简单的单元测试来演示问题,但在其他方面没有多大意义:

#nullable enable
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CSharpRecordTest {

  record Twin(string Name) {
    public Twin? OtherTwin { get; set; }
  }

  [TestClass]
  public class UnitTest1 {
    [TestMethod]
    public void TestMethod1() {
      var twinA = new Twin("A");
      var twinB = new Twin("B");
      twinA.OtherTwin = twinB;
      twinB.OtherTwin = twinA;
      Assert.AreEqual(twinA, twinA.OtherTwin.OtherTwin);
    }
  }
}

测试运行良好,但是在 Assert.AreEqual( 设置断点并将鼠标移到 twinA 上时,调试会话停止并显示以下错误消息:

在此处输入图像描述

标签: c#c#-9.0

解决方案


我花了一两天的时间才弄清楚发生了什么,因为调试器没有让我看到任何东西。我写了一个控制台应用程序:

class Program {
  record Twin(string Name) {
    public Twin? OtherTwin { get; set; }
  }

  static void Main(string[] args) {
    var twinA = new Twin("A");
    var twinB = new Twin("B");
    twinA.OtherTwin = twinB;
    twinB.OtherTwin = twinA;
    Console.WriteLine(twinA);
  }
}

控制台应用程序也遇到了麻烦,但至少它显示了堆栈溢出以及它导致了哪一行:

Console.WriteLine(twinA);

堆栈看起来像这样(虽然更复杂):

twinA.OtherTwin.OtherTwin.OtherTwin.OtherTwin.OtherTwin.OtherTwin...OtherTwin.ToString()

问题是编译器自动编写的 ToString() 会在每个属性上再次调用 .ToString()。

如果一条记录引用了它自己或其他引用了第一条记录的记录,ToString() 将失败,需要与 Equals()、GetHashCode() 甚至更多(我没有尝试过)一起被覆盖。

实际上,当具有非只读属性时,应该重写 Equals() 和 GetHashCode(),否则 Dictionary 之类的类将不起作用。

更多详情请看我在 CodeProject 上的文章:C# 9 Record: Compiler Created ToString() Code can Lead to Stack Overflow and Worse


推荐阅读