类的StackOverflowException [英] StackOverflowException with class
问题描述
我写的课程有问题.当我尝试调用它时,出现异常.请参阅下面的代码以更清楚.
我上课了:
I have a problem with a class that I wrote. When I try to call it I get an exception. See the code below for more clarity.
I have the class:
using System;
using System.Data;
namespace People
{
class Person
{
// Auto prop + field
public string Name
{
get { return this.Name; }
private set
{
if (string.IsNullOrEmpty(value))
{
throw new NoNullAllowedException("Name is mandatory");
}
else
{
this.Name = value;
}
}
}
// Auto prop + field
public int Age
{
get { return this.Age; }
private set
{
if (value <= 0 || value > 100)
{
throw new Exception("Age must be between 1 and 100");
}
else
{
this.Age = value;
}
}
}
// Auto prop + field
public string Email
{
get { return this.Email; }
private set { this.Email = value; }
}
// Constructor 1
public Person(string name, int age, string email)
{
this.Name = name;
this.Age = age;
this.Email = email;
}
// Constructor 2
public Person(string name, int age) : this(name,age,"")
{
}
// Write to console
public override string ToString()
{
return string.Format("Name: {0} \nAge: {1} \nEmail: {2}" ,Name,Age,Email);
}
}
}
当我叫这堂课时:
Person someone = new Person("First Someone",51,"someone@gmail.com");
Console.WriteLine(someone);
我得到:
进程由于StackOverflowException而终止.
Process is terminated due to StackOverflowException.
我看不到问题.
预先谢谢你.
I can't see the problem.
Thank you in advance.
推荐答案
问题是,当您尝试获取或设置任何属性(例如 Name
)时,存在一个代码路径调用具有相同属性的设置器:
The problem is that when you try to get or set any of the properties, say, Name
, there is a code path that calls the setter of the same property:
public string Name
{
get { return this.Name; } // <<<<====== HERE
private set
{
if (string.IsNullOrEmpty(value))
{
throw new NoNullAllowedException("Name is mandatory");
}
else
{
this.Name = value; // <<<<==== HERE
}
}
}
this.Name
的意思是用 value
的值调用 Name
的获取器/设置器".这将导致无限递归,从而导致堆栈溢出.
this.Name
means "call getter/setter of Name
with the value of value
". This creates infinite recursion, causing stack overflow.
要使用诸如此类的条件来实现属性,您需要定义存储实际数据的字段.一种常见的方法是将这些字段设为私有,并使用与属性相同的名称来命名它们,但首字母不应大写:
To implement properties with conditions like that you need to define fields that store the actual data. A common approach is to make these fields private, and name them with the same name as the property, except the first letter should not be capitalized:
private string name; // <<<<==== Add this
public string Name
{
get { return name; } // <<<<====== change
private set
{
if (string.IsNullOrEmpty(value))
{
throw new NoNullAllowedException("Name is mandatory");
}
else
{
name = value; // <<<<==== change
}
}
}
这篇关于类的StackOverflowException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!