C# 为什么抽象类可以有构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19944644/
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 can an abstract class have constructor?
提问by Aslam Jiffry
Why does an abstract class have constructor? What's the point? It's obvious that we cannot create an instance of an abstract class.
为什么抽象类有构造函数?重点是什么?很明显,我们不能创建抽象类的实例。
采纳答案by P.Brian.Mackey
One important reason is due to the fact there's an implicit call to the base constructor prior to the derived constructor execution. Keep in mind that unlike interfaces, abstract classes do contain implementation. That implementation may require field initialization or other instance members. Note the following example and the output:
一个重要的原因是在派生构造函数执行之前存在对基构造函数的隐式调用。请记住,与接口不同,抽象类确实包含实现。该实现可能需要字段初始化或其他实例成员。请注意以下示例和输出:
abstract class Animal
{
public string DefaultMessage { get; set; }
public Animal()
{
Console.WriteLine("Animal constructor called");
DefaultMessage = "Default Speak";
}
public virtual void Speak()
{
Console.WriteLine(DefaultMessage);
}
}
class Dog : Animal
{
public Dog(): base()//base() redundant. There's an implicit call to base here.
{
Console.WriteLine("Dog constructor called");
}
public override void Speak()
{
Console.WriteLine("Custom Speak");//append new behavior
base.Speak();//Re-use base behavior too
}
}
Although we cannot directly construct an Animal
with new
, the constructor is implicitly called when we construct a Dog
.
虽然我们不能直接构造一个Animal
with new
,但是当我们构造一个 时,构造函数会被隐式调用Dog
。
OUTPUT:
Animal constructor called
Dog constructor called
Custom Speak
Default Speak
输出:
动物构造函数称为
狗构造函数,称为
自定义说话
默认说话
回答by AD.Net
You can still initialize any variables, dependencies and you can set up the signature of the constructors of the inherited classes.
您仍然可以初始化任何变量、依赖项,并且可以设置继承类的构造函数的签名。
You usually want abstract classes when you need to have different strategies for some particular cases, so it makes sense to be able to do everything else in the abstract class. And it's a good practice to make the constructor protected
.
当您需要针对某些特定情况采用不同的策略时,您通常需要抽象类,因此能够在抽象类中执行其他所有操作是有意义的。制作构造函数是一个很好的做法protected
。