c# - StackOverflowException 未处理

标签 c# .net exception-handling stack-overflow

我的代码中有这个错误

An unhandled exception of type 'System.StackOverflowException' occurred in MedCareProviderLibrary.dll

这是我的代码片段以及错误的来源。它在有错误的部分给出了一个黄色箭头。

显示错误的部分以粗体显示。任何帮助将不胜感激谢谢

private string _TestNo;
private string _TestType;
private DateTime _TestDate;
private string _PatientNo;
private string _DoctorNo;

public Test()
{
    _TestNo = "";
    _TestType = "";
    _TestDate = new DateTime();
    _PatientNo = "";
    _DoctorNo = "";
}

public Test(string aTestNo, string aTestType, DateTime aTestDate, string aPatientNo, string aDoctorNo)
{
    _TestNo = aTestNo;
    _TestType = aTestType;
    _PatientNo = aPatientNo;
    _DoctorNo = aDoctorNo;
}

public string TestNo
{
    set { _TestNo = value; }
    get { return (TestNo); }
}    

public string TestType
{
    set { _TestType = value; }
    **get { return (TestType); }
}

public DateTime TestDate
{
    set { _TestDate = value; }
    get { return (TestDate); }
}

public string PatientNo
{
    set { _PatientNo = value; }
    get { return (PatientNo); }
}

public string DoctorNo
{
    set { _DoctorNo= value; }
    get { return (DoctorNo); }
}

最佳答案

您所有的属性 getter 都返回属性本身,而不是下划线前缀的字段名称。

public string TestType
{
    set { _TestType = value; }
    get { return (TestType); }
}

您执行的不是return _TestType,而是return TestType,因此属性 getter 会一次又一次地访问自身,导致无限递归并最终导致调用堆栈溢出.

此外,返回值不一定需要括号(除非您正在评估一些复杂的表达式,在这种情况下您不需要)。

更改您的 getter 以返回带下划线前缀的字段(为您的所有属性执行此操作):

public string TestType
{
    set { _TestType = value; }
    get { return _TestType; }
}

或者制作它们 automatic properties正如其他人建议的那样,如果您使用的是 C# 3.0。

关于c# - StackOverflowException 未处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5676430/

相关文章:

c# - 在 C# 中更改 WebBrowser 控件的显示字体?

c# - Nancy 的 Html.Render Context.Context.CurrentUser 抛出异常

c++ - 使用 Qt5 的 throw 语句即时崩溃

java - 使用 Try Catch 异常处理或显式检查

c# - Caliburn.Micro DisplayRootViewFor 抛出 NullReferenceException

c# - 从类实例定义默认数组值

c# - 从 appsettings c# 读取 json 数组

c# - 哪个是更好的选择? - 在 Web 控件的 Viewstate 中的局部变量或存储变量

c# - F# 轻量级脚本环境

C++ catch block - 通过值或引用捕获异常?