C# 带有类的StackOverflowException
C# 带有类的StackOverflowException,c#,class,C#,Class,我写的一个类有问题。当我尝试调用它时,我得到一个异常。请参阅下面的代码以了解更多信息。 我有一门课: using System; using System.Data; namespace People { class Person { // Auto prop + field public string Name { get { return this.Name; } private set {
我写的一个类有问题。当我尝试调用它时,我得到一个异常。请参阅下面的代码以了解更多信息。
我有一门课:
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);
}
}
}
我得到:
进程因StackOverflowException而终止
我看不出有什么问题。提前谢谢。更改
get { return this.Name; }
到
年龄属性也是如此
这是因为This.Name正在使用您正在重写的get方法,因此创建了StackOverflowException!如果您需要名称和年龄字段,您必须自己创建一个,如:
private string name;
public string Name
{
get { return this.name; }
private set
{
if (string.IsNullOrEmpty(value))
{
throw new NoNullAllowedException("Name is mandatory");
}
else
{
this.name = value;
}
}
}
问题在于,当您尝试获取或设置任何属性(例如,
Name
)时,存在一个调用同一属性的setter的代码路径:
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
}
}
}
您的属性在getter上调用自己。您可以阅读以下内容:。它详细解释了属性。请您解释一下,为什么这会有帮助,以便OP理解他的错误?
private string name;
public string Name
{
get { return this.name; }
private set
{
if (string.IsNullOrEmpty(value))
{
throw new NoNullAllowedException("Name is mandatory");
}
else
{
this.name = value;
}
}
}
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
}
}
}
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
}
}
}