加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#中的抽象类构造函数

发布时间:2020-12-15 20:48:27 所属栏目:百科 来源:网络整理
导读:在c#中,我们无法创建一个抽象类或接口的对象,这意味着抽象类没有任何构造函数,是真的吗? 或者如果它有那么它的目的是什么? 解决方法 好问题.这就是为什么抽象类需要构造函数,即使它们无法即时生成. 在任何面向对象的语言(如C#)中,对象构造是一个分层过程.
在c#中,我们无法创建一个抽象类或接口的对象,这意味着抽象类没有任何构造函数,是真的吗?
或者如果它有那么它的目的是什么?

解决方法

好问题.这就是为什么抽象类需要构造函数,即使它们无法即时生成.

在任何面向对象的语言(如C#)中,对象构造是一个分层过程.看下面的代码.当您实例化DerivedClass类型的任何对象时,它必须在创建typeof DerivedClass的对象之前首先构造基础对象.这里的基类可能是也可能不是抽象类.但即使你实例化一个从抽象类派生的具体类型的对象,它仍然需要在创建DerivedClass类型的对象之前调用Base类的构造函数,因此你总是需要一个Abstract类的构造函数.如果您尚未添加任何构造函数,C#编译器将自动向生成的MSIL中的类添加公共无参数构造函数.

public class BaseClass
{
    public BaseClass() 
    {
        Console.WriteLine("BaseClass constructor called..");
    }
}

public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
        Console.WriteLine("DerivedClass constructor called..");
    }
}

DerivedClass obj = new DerivedClass();

//Output
//BaseClass constructor called..
//DerivedClass constructor called..

PS: Assuming,If Abstract base classes are not allowed to have constructors because they need not be instantiated,the whole fundamentals of the object oriented programming will go on toss. The idea behind Abstract types are to represent objects that have some features and behaviours but not complete as whole to allow independant existence.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读