简体   繁体   English

在同一个类c#中的构造函数中调用构造函数,并在同一个构造函数中调用base Constructor

[英]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 A继承自class B class A class B class B has the following Constructor: class B有以下构造函数:

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

Class A has a default constructor . A具有默认的构造函数 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 ? 是否有实现的构造函数的方式class A这就要求从基本构造 class B ,并呼吁从默认构造函数 class A Something which can use base and this : 可以使用base东西, 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 ?) 你的代码没有编译public A()没有办法调用base B(int num)构造函数(应该作为num传递什么?)

You can move logic from A() to A(int num) and use constructor chaining to implement A() 您可以将逻辑从A()移动到A(int num)并使用构造函数链接来实现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)
        {

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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