Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
VS2005中的C#:在继承类中,是否需要显式调用超级构造函数?_C#_Inheritance - Fatal编程技术网

VS2005中的C#:在继承类中,是否需要显式调用超级构造函数?

VS2005中的C#:在继承类中,是否需要显式调用超级构造函数?,c#,inheritance,C#,Inheritance,如果在C#(VS2005)中创建继承类,是否需要显式调用更高类的构造函数,还是会自动调用它?如果未提供默认(无参数)构造函数,将自动调用它 换句话说,它们是等价的: public Foo() : base() {} 及 假设Foo的基有一个无参数构造函数 另一方面,如果基仅具有具有如下参数的构造函数: protected MyBase(IBar bar) {} 然后 不会编译。在这种情况下,必须使用适当的参数显式调用base-例如 public Foo(IBar bar) : base(ba

如果在C#(VS2005)中创建继承类,是否需要显式调用更高类的构造函数,还是会自动调用它?

如果未提供默认(无参数)构造函数,将自动调用它

换句话说,它们是等价的:

public Foo() : base() {}

假设Foo的基有一个无参数构造函数

另一方面,如果基具有具有如下参数的构造函数:

protected MyBase(IBar bar) {}
然后

不会编译。在这种情况下,必须使用适当的参数显式调用base-例如

public Foo(IBar bar) : base(bar) {}

如果基类具有将自动调用的默认构造函数。如果没有默认构造函数,则必须显式调用一个。

如果未指定默认构造函数,则会自动调用基类的默认构造函数

示例代码:

public class ClassA
    {

        protected bool field = false;

        public ClassA()
        {
            field = true;
        }
    }

    public class ClassB : ClassA
    {
        public ClassB()
        {
        }

        public override string ToString()
        {
            return "Field is " + field.ToString();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ClassB target = new ClassB();

            Console.WriteLine(target.ToString());

            Console.ReadKey();
        }
    }

这将显示'field'值被设置为true,即使ClassB没有显式调用ClassA构造函数。

您想在第二个示例中添加{}。
public Foo(IBar bar) : base(bar) {}
public class ClassA
    {

        protected bool field = false;

        public ClassA()
        {
            field = true;
        }
    }

    public class ClassB : ClassA
    {
        public ClassB()
        {
        }

        public override string ToString()
        {
            return "Field is " + field.ToString();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ClassB target = new ClassB();

            Console.WriteLine(target.ToString());

            Console.ReadKey();
        }
    }