C# 为什么抽象类的构造函数应该受到保护,而不是公共的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/761854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why should constructors on abstract classes be protected, not public?
提问by Cristian Diaconescu
ReSharper suggests changing the accessibility of a public
constructor in an abstract
class to protected
, but it does not state the rationale behind this.
ReSharper 建议将类中public
构造函数的可访问性更改abstract
为protected
,但并未说明其背后的基本原理。
Can you shed some light?
你能说明一下吗?
采纳答案by JaredPar
Simply because being public makes no sense in an abstract class. An abstract class by definition cannot be instantiated directly. It can only be instantiated by an instance of a derived type. Therefore the only types that should have access to a constructor are its derived types and hence protected makes much more sense than public. It more accurately describes the accessibility.
仅仅因为在抽象类中公开是没有意义的。根据定义,抽象类不能直接实例化。它只能由派生类型的实例实例化。因此,唯一应该访问构造函数的类型是它的派生类型,因此 protected 比 public 更有意义。它更准确地描述了可访问性。
回答by Srikar Doddi
It is good OO practice.
这是很好的面向对象实践。
public abstract class ExampleAbstractClass
{
protected ExampleAbstractClass()
{
// :::
}
}
You only want the inheriting child classes to have access to the constructor. The only way to do that is by making the constructor protected.
Keep in mind, when you add parameters to these constructors, it is an entirely different discussion.
您只希望继承的子类可以访问构造函数。做到这一点的唯一方法是使构造函数受到保护。
请记住,当您向这些构造函数添加参数时,这是一个完全不同的讨论。
回答by Daniel A.A. Pelsmaeker
It technically makes no difference whatsoever if you make the constructor public
instead of protected
on an abstract class. The accessibility/visibility of the constructor is still exactly the same: the same class or derived classes. The two keywords have indistinguishable effects for all intents and purposes.
如果您使用构造函数public
而不是protected
抽象类,那么从技术上讲,它没有任何区别。构造函数的可访问性/可见性仍然完全相同:相同的类或派生类。这两个关键字对于所有意图和目的都具有无法区分的效果。
So, this choice is only a matter of style: type protected
to satisfy the Object Oriented savvy people.
所以,这个选择只是风格问题:类型protected
以满足面向对象的精明人士。
Reflection will by default only include the constructor when it is public
, but you cannot call that constructor anyway.
默认情况下,反射将仅包含构造函数public
,但无论如何您都不能调用该构造函数。
IntelliSense will show the public
constructor when typing new
, but you cannot call that constructor anyway.
IntelliSense 将public
在键入时显示构造函数new
,但无论如何您都无法调用该构造函数。
The assembly's metadata will reflect the fact that the constructor is public or protected.
程序集的元数据将反映构造函数是公共的还是受保护的这一事实。