在C#中,你需要调用基构造函数? [英] In C#, do you need to call the base constructor?

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

问题描述

在C#中,如果我有一个默认的构造函数的继承类,我必须显式调用基类的构造函数或将它隐式调用?

In C#, if I have an inherited class with a default constructor, do I have to explicitly call the base class' constructor or will it be implicitly called?

class BaseClass
{
    public BaseClass()
    {
        // ... some code
    }
}
class MyClass : BaseClass
{
    public MyClass() // Do I need to put ": base()" here or is it implied?
    {
        // ... some code
    }
}


推荐答案

您无需显式调用基类的构造,它会被隐式调用。

You do not need to explicitly call the base constructor, it will be implicitly called.

扩展你的榜样一点点,并创建一个控制台应用程序,你可以验证自己这种行为:

Extend your example a little and create a Console Application and you can verify this behaviour for yourself:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass foo = new MyClass();

            Console.ReadLine();
        }
    }

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

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

这篇关于在C#中,你需要调用基构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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