FxCop 抽象类型在没有 new 时不应有构造函数
我对 FxCop 存在疑问,并收到警告:抽象类型不应具有构造函数
。
这是为许多抽象类(可能是所有,我还没有检查)显示的。当我看到它们中的大多数都没有新方法时,所以我认为是编译器添加了默认方法。因此,为了删除它,我添加了一个私有默认构造函数(Private Sub New()
),这意味着所有继承类都无法构建并出现错误: 类“InheritingClass”没有可访问的“Sub New”并且无法继承。
这看起来很奇怪,因为 FxCop 不请求公共构造函数,但当我删除它时,构建失败。
I have an issue with FxCop and the warning: Abstract types should not have constructors
.
This is being displayed for a number of abstract classes (possibly all, I haven't checked). When I look most of them have no new method so I assume it's the complier adding a default one. So to remove it I add a private default constuctor (Private Sub New()
), this then means all the inherting classes fail to build with the error:Class 'InheritingClass' has no accessible 'Sub New' and cannot be inherited.
This seems odd as FxCop requests no public constructor, but when I remove it the build fails.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试向抽象类添加一个受保护的无参数构造函数。
当您不提供构造函数时,编译器会为您添加一个公共无参数构造函数。显然,抽象类拥有公共构造函数是不合适的,因为无论如何它们都受到有效保护 - 抽象类型的构造函数充其量可以被子类调用(这就是抽象类型的全部要点 - 它不能被实例化为“普通”)。这一设计缺陷正是 FxCop 抱怨的原因。
另一方面,您为解决问题所采取的措施过于极端; 仅具有私有构造函数的类(抽象或非抽象)在实践中不可子类化(嵌套类除外) - 没有隐式或显式的
base(...)
可能在派生类的构造函数中工作的构造函数调用。编辑:我喜欢此MSDN页面的方式说:
Try adding a protected, parameterless constructor to the abstract class instead.
When you don't provide a constructor, the compiler adds a public, parameterless one for you. Clearly, it isn't appropriate for an abstract class to have public constructors since they are effectively protected anyway - constructors on abstract types can at best be called by subclasses (that's the whole point of an abstract type - it can't be instantiated 'vanilla'). This design flaw is what causes FxCop to complain.
On the other hand, the step you took to fix the issue was too extreme; classes (abstract or not) that have only private constructors are not subclassable in practice (except by a nested class) - there is no implicit or explicit
base(...)
constructor-call that could possibly work in a derived class's constructor.EDIT: I like the way this MSDN page puts it: