FxCop 抽象类型在没有 new 时不应有构造函数

发布于 2024-10-04 08:36:43 字数 304 浏览 0 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感悟人生的甜 2024-10-11 08:36:43

尝试向抽象类添加一个受保护的无参数构造函数。

当您不提供构造函数时,编译器会为您添加一个公共无参数构造函数。显然,抽象类拥有公共构造函数是不合适的,因为无论如何它们都受到有效保护 - 抽象类型的构造函数充其量可以被子类调用(这就是抽象类型的全部要点 - 它不能被实例化为“普通”)。这一设计缺陷正是 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:

In the example above abstract type has
a public constructor, which can
confuse users. They see the public
constructor, but do not understand why
they are unable to create the type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文