摘要构造函数在C# [英] Abstract constructor in C#

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

问题描述


可能重复:结果
我为什么不能创建一个抽象的C#类的抽象构造?






为什么我不能在我的声明类抽象的构造是这样的:

 公共抽象类MyClass的{
公共抽象MyClass的(INT参数);
}


解决方案

构造函数是仅适用于它们所定义的类,也就是说,他们是不能继承的。基类的构造函数使用(你必须调用其中的一个,哪怕只是调用默认的自动)通过派生类,但不覆盖。可以在一个抽象基类定义构造 - 它不能直接使用,但可以通过导出类中调用。你不能做的是强制派生类实现特定的构造函数签名。



这是因为保护完全合理的有一个构造函数定义,通常情况下,为了定义所有派生类一些常见的设置代码。这是特别真实的,或许,当抽象类提供依赖于这一套一些其他默认行为。例如:

 公共抽象类Foo 
{
公共字符串名称{;私人集; }

保护美孚(字符串名称)
{
this.Name =名称;
}
}

公共类酒吧:富
{
公开栏():基地(巴)
{
...
}
}


Possible Duplicate:
Why can’t I create an abstract constructor on an abstract C# class?

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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆