开发者

Call base constructor and other constructor in constructor

开发者 https://www.devze.com 2023-03-13 04:00 出处:网络
Title may sound confusing. What I want is to call a 开发者_StackOverflow社区constructor of the same class and the constructor of the base class inside a constructor.

Title may sound confusing. What I want is to call a 开发者_StackOverflow社区constructor of the same class and the constructor of the base class inside a constructor. Maybe my first attempt to solve that may explain my question:

public MyClass(MyClass obj) : base(obj),this() {}

But that notation isn't working. Is there any solution to solve that?


No, you can't do it for the following reason:

When a constructor calls the constructor of its base, the latter call is THE PART of the constructor in question. So you can't call another constructor of the same class AND a constructor of a base class because the former call already contains a call to a base constructor - you can't initialize your base twice


C# allows either base(...) or this(...), because every constructor must eventually invoke a super constructor. So if it were possible to invoke both base() and this(), two super constructors invocations would take place, which would be fundamentally incorrect.

It is the same reason why it is not possible to invoke base(...) twice.


No technical solution for this, you need a workaround, move logic out of the default constructor, make the base call a virtual function than override at your super class.


One way would be to make the parameterless constructor of MyClass to call base(obj). But if you don't always want to do that, than I don't think there is a good way.

Maybe you can try to move stuff around in those constructors. Can you post more info about what actually happens in these constructors?


You could simply copy the constructor code into the given constructor. Or make a special setup() function that is called from the default constructor and this constructor.


In C# you may also provide a default initialization in the declaration for each member:

private int foo_ = 41;

This solves for many use-other-constructor issues.


Actually, you CAN do so, You can fire the parent class constructor from the child class instance, here is how you do it:

public class Person
{
    public Person(int age) {
        this.Age = age; 
    } 
    public int Age;
}

public class students :Person
{
    public students(string name, int age) :base(age ) 
    { 
        this.studentName = name;
        this.Age = age;
    }

    public string studentName;
}

Now, lets say you are creating an object from students class, So, you will do this:

students std = new students ("Jack", 23);

This will send "Jack" to students class constructor, and 23 will be send to Person constructor via :base(age)

Hope this help, Cheers.

0

精彩评论

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