C# 抽象类中的公共构造函数有什么用?
如果抽象类中的公共构造函数只能由其派生类调用,那么它在功能上应该等同于受保护的构造函数。正确的?
在抽象类中声明公共构造函数而不是受保护的构造函数有什么区别吗?你会用它做什么?为什么编译器不抱怨?
If a public constructor in an abstract class can only be called by their derived classes it should be functionally equivalent to a protected constructor. Right?
Is there any difference in declaring a public constructor, instead of a protected one, in an abstract class? What would you use it for? Why the compiler doesn't complaint?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
绝对正确。您应该青睐受保护的构造函数。
编辑:不,编译器不会抱怨,但像 FxCop(和代码分析)这样的工具会抱怨。我相信您可以使用抽象类上的公共构造函数执行一些奇怪的反射技巧,但从仅向编写子类的其他开发人员提供基类功能的角度来看,请坚持使用受保护的构造函数。
Absolutely correct. You should favor the protected constructor.
EDIT: no the compiler doesn't complain, but tools like FxCop (& Code Analysis) do. I believe there are some weird reflection tricks you can do with public constructors on abstract classes, but from a standpoint where you are merely providing base class functionality to other developers writing subclasses, stick with the protected constructor.
你是对的。抽象类中的公共构造函数在功能上等同于受保护的构造函数。
在这种情况下,我更喜欢使用受保护的构造函数。
虽然编译器确实不会抱怨您这样做,但编译器会抱怨尝试生成抽象类的实例。 Visual Studio 也足够聪明,如果您尝试实例化抽象类,它不会提供 Intellisense。
You are correct. A public constructor in an abstract class is functionally equivalent to a protected constructor.
I prefer to use a protected constructor in this case.
While, it is true that the compiler will not complain about you doing this, the compiler will complain about trying to generate an instance of the abstract class. Visual Studio is smart enough, as well, to not provide Intellisense if you try to instantiate the abstract class.
是的,你是对的,实际上公共构造函数在抽象类中没有用,因为你无法创建它们。
然而编译器不会抱怨,因为这样你可以在c#上下文中编写很多无用的东西,但它无法检查其逻辑含义,它只能检查它所设置的解析规则。
当然,c# 创建者专注于创建实际上有害且违反语言使用的编译语法(规则)。
Yes, you are right, practically public constructor has no use in abscract class as you cant create them.
However compiler will not complain because that way there are so many useless things you can write in context of c#, but it will not be able to check its logical meaning, it can only check the parsing rules which it is set for.
And sure c# creators have focused on creating compilation grammar (rules) that are actual harmful and violating the language use.