c# - 使用属性和继承的构造函数时出现意外的 StackOverflow 异常
问题描述
在 C# 中使用继承和属性(出于教学原因)玩弄一个奇怪的异常。对于专家来说应该是小菜一碟,但仍然让我感到困惑。这是我的代码:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
public class Employee : Person
{
public int ID
{
get
{
return ID;
}
set
{
if (ID < 0 || ID > 999)
throw new Exception("Id must between [000-999]");
ID = value;
}
}
public Employee(string name, int age, int id):base(name, age)
{
ID = id;
}
}
static void Main(string[] args)
{
var per = new Person("John", 32);
var imp = new Employee("Michael", 44, 330);
}
执行我得到了一个 StackOverflow。最后一个 StackTrace 指向 Employee 类中 Employee.get_ID () 行的错误。
提前感谢您的任何帮助!
解决方案
好吧,财产会自己ID
回来
public int ID
{
get
{
return ID;
}
...
因此你有堆栈溢出:当你读取ID
它时调用ID
它反过来调用ID
等。同样的问题set
:你为属性ID
赋值,导致赋值给ID
等。为了打破这个恶性循环,让我们引入一个支持字段
private int m_ID;
public int ID
{
get
{
//DONE: now we just read m_ID, not call the property
return m_ID;
}
set
{
//DONE: you want to validate value, not ID, right?
//DONE: ArgumentOutOfRangeException - value is out of valid range
if (value < 0 || value > 999)
throw new ArgumentOutOfRangeException(nameof(value),
"Id must between [000-999]");
//DONE: we assign value to the field, not to the property
m_ID = value;
}
}
推荐阅读
- swift - 如何使用 Codable 解析不同对象列表的 Json 数组?
- javascript - 如果 location.state 为空,则反应路由器重定向
- django-channels - 如何设置 django-channels ChannelsLiveServerTestCase 服务器端口?
- c# - 外壳导航
- wget - 无法下载 ADYEN 报告
- c++ - 我在 Visual Studio Code 中的 C++ 代码显示错误 AccessDenied
- python - 设置列表值的更好方法
- reactjs - 验证 MongoDB 中是否有任何文档
- dart - dart 中是否有 C++ setw() 的等价物?
- python - 在 Django 的 cognito 上使用 JWT id 令牌检索有效负载的正确方法