开发者

C# in VS2005: in an inherited class, do you need to explicitly call the super-constructor?

If you make an inherited class in C# (VS2005) do you need to explicitly cal开发者_JAVA技巧l the constructor of the higher class, or will it be called automatically?


The default (parameterless) constructor will automatically be invoked if not supplied.

In other words, these are equivalent:

public Foo() : base() {}

and

public Foo() {}

assuming that Foo's base has a parameterless constructor.

On the other hand, if the base only has a constructor with parameters like this:

protected MyBase(IBar bar) {}

then

public Foo() {}

will not compile. In this case you must explicitly call the base with the appropriate parameter - e.g.

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


If the base class has a default constructor that will be invoked automatically. If there is no default constructor you must invoke one explicitly.


The base class' default constructor will be automatically called if you do not specify one.

Example code:

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();
        }
    }

This will show that the 'field' value is set to true, even though the ClassA constructor was not explicitly called by ClassB.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜