开发者

Constructor chaining in conjunction with the base constructor invocation

开发者 https://www.devze.com 2023-02-13 19:24 出处:网络
Say I have the following: class Base { public Base (int n) { } public Base (Object1 n, Object2 m) { } } class Derived : Base {

Say I have the following:

class Base {
    public Base (int n) { }
    public Base (Object1 n, Object2 m) { }
}

class Derived : Base {

    string S;

    public Derived (string s, int n) : base(n) {
        S = s;
    }

    public Derived (string s, Object1 n, Object2 m) : base(n, m) {
        S = s; // repeated
    }
}

Notice how I need formal argument n in both overloads of the Derived and thus I have to repeat the N = n; line.

Now I know that this can be encapsulated into a separate method but you still need the same two method calls from both overloads. So, is there a more 'elegant' way of doing this, maybe by using this in conjunction with base?

This i开发者_Python百科s so that I can have a have a private constructor taking one argument s and the other two overloads can call that one...or is this maybe just the same as having a separate private method?


There is no ideal solution for that. There is a way to avoid repeating the code in the Derived constructors, but then you have to repeat the default value of the m parameter:

public Derived (string s, int n) : this(s, n, 0) {}


Only a slight improvement, but...

class Derived : Base
{
    string S;
    public Derived(string s, int n) : this(s,n,-1)
    {
    }

    public Derived(string s, int n, int m) : base(n, m)
    {
        S = s;
        // repeated    
    }
}
0

精彩评论

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