英文:
Purpose of setting Class Property as virtual without any kind of interface?
问题
最近我换了工作。在这里,我查看了代码,发现了"virtual"关键字,并确认它不是任何继承的一部分。我尝试在Google上搜索,但找不到令人满意的答案。以下是参考的代码:
public class Department
{
public virtual int DepartmentId { get; private set; }
public Department(int departmentId)
{
this.DepartmentId = departmentId;
}
}
有人可以解释这里的"virtual"关键字的用途吗?
英文:
Recently I have switched the Job. Here I have gone through the code where I found the "virtual" keyword and I have confirmed that it is not part of any kind of inheritance. I tried to search on google but could not find the satisfactory answer. Below is the code for the reference:
public class Department
{
public virtual int DepartmentId { get; private set; }
public Department(int departmentId)
{
this.DepartmentId = departmentId;
}
}
Can anyone explain the use of virtual here?
答案1
得分: 5
这意味着如果一些未来的子类Foo:Department
希望,它可以重写该属性以更改访问器的行为。这似乎是一个不太可能的要求,你不应该默认将事物设为virtual
- 多态性应该经过设计和测试。特别是在构造函数中调用virtual
成员有点危险,这就是构造函数现在会做的事情;理论上,这意味着您可能会在子类构造函数执行之前调用setter上的子类override
,这意味着状态可能是不确定的。
英文:
It means that if some future subclass Foo : Department
wishes, it can override that property to change the behavior of the accessors. This seems an unlikely requirement, and you shouldn't make things virtual
by default - polymorphism should be designed for and tested. In particular, calling a virtual
member in a constructor is a bit dangerous, which is what the constructor would now do; in theory this means that you could end up with a scenario where the sub-class override
on the setter gets invoked before the sub-class constructor has executed, which means the state may be indeterminate.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论