中的抽象构造函数

中的抽象构造函数

本文介绍了C#中的抽象构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
为什么我不能创建抽象 C# 类上的抽象构造函数?

为什么我不能像这样声明我的类的抽象构造函数:

Why I can't declare abstract an constructor of my class like this:

public abstract class MyClass {
    public abstract MyClass(int param);
}

推荐答案

构造函数只适用于定义它们的类,即不能被继承.使用基类构造函数(您必须调用其中之一,即使仅自动调用默认构造函数)但不会被派生类覆盖.您可以在抽象基类上定义构造函数——它不能直接使用,但可以通过派生类调用.您不能做的是强制派生类实现特定的构造函数签名.

Constructors are only applicable to the class in which they are defined, that is, they are not inherited. Base class constructors are used (you have to call one of them, even if only calling the default one automatically) but not overridden by deriving classes. You can define a constructor on an abstract base class -- it can't be used directly, but can be invoked by deriving classes. What you can't do is force a derived class to implement a specific constructor signature.

定义一个构造函数是完全合理的,通常被定义为受保护的,以便为所有派生类定义一些通用的设置代码.当抽象类提供一些依赖于此设置的其他默认行为时,尤其如此.例如:

It is perfectly reasonable to have a constructor defined, typically as protected, in order to define some common set up code for all derived classes. This is especially true, perhaps, when the abstract class provides some other default behavior which relies on this set up. For example:

public abstract class Foo
{
     public string Name { get; private set; }

     protected Foo( string name )
     {
         this.Name = name;
     }
}

public class Bar : Foo
{
     public Bar() : base("bar")
     {
        ...
     }
}

这篇关于C#中的抽象构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:47