简体   繁体   中英

Calling Constructor with in constructor in same class c# and calling to base Constructor in the same Constructor

I have class A which inherits from class B . class B has the following Constructor:

public class B
{
    public B(int num) { ... }
}

Class A has a default constructor . Is there a way to implement a Constructor in class A which calls the base constructor from class B and calls the default constructor from class A ? Something which can use base and this :

public class A : B
{
    public A() { ... }

    public A(int num) : base(num), this()
    { ... }
}

Your code doesn't compile : there is no way for public A() to call base B(int num) constructor (what should be passed as num ?)

You can move logic from A() to A(int num) and use constructor chaining to implement A()

public class A : B
{
    public A(): this(0) {} //TODO: provide default num here

    public A(int num) : base(num)
    { 
        //TODO: implement logic here
    }
}

You can use static constructor like this

public class B
    {
        public B(int num)
        {
            Console.Write("B");
        }
    }

    public class A : B
    {
        static A()
        {
            Console.Write("A");
        }

        public A(int num) : base(num)
        {

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM