我有一个类是其他一些类的基础。该类有一个虚拟方法,它应该在派生类中被覆盖。它是这样定义的:
protected virtual TableFormat GetFormat()
{
throw new NotImplementedException("Implement the format generator in derived class.");
}
这是好的做法吗?我的老板告诉我 NotImplementedException 应该只用于自动生成的代码,但在他给出理由之前我拒绝遵守。
此外,这似乎是在非抽象类中使用抽象方法的好地方。为什么不允许这样做?
请您参考如下方法:
Is this a good practice?:
IMO,最好抛出 NotImplementedException,因为如果您返回 null,您还会返回什么,您的类的用户永远不会知道这个方法必须是覆盖。所以我不同意你的老板。
this seems like a good place to have an abstract method in a nonabstract class. Why is this not allowed?
您可能会看到讨论:Abstract Method in Non Abstract Class
I have a class that is a base for some other classes. The class has a virtual method, which is supposed to be overridden in the derived classes.
为什么不将方法定义为abstract而不是虚拟的。
Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation.
但是
- An abstract method is implicitly a virtual method.
- Abstract method declarations are only permitted in abstract classes.
- Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration
simply ends with a semicolon and there are no curly braces ({ })
following the signature.
