构造函数链接与基本构造函数调用相结合

发布于 2024-10-19 11:35:33 字数 625 浏览 2 评论 0原文

假设我有以下内容:

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
    }
}

请注意,在 Derived 的两个重载中我如何需要形式参数 n,因此我必须重复 N = n; 行。

现在我知道这可以封装到一个单独的方法中,但您仍然需要从两个重载中调用相同的两个方法。那么,是否有一种更“优雅”的方式来做到这一点,也许可以将 thisbase 结合使用?

这样我就可以拥有一个带有一个参数 s 的私有构造函数,而其他两个重载可以调用该参数......或者这可能与拥有一个单独的私有方法相同吗?

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 is 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寄离 2024-10-26 11:35:34

对此没有理想的解决方案。有一种方法可以避免在 Derived 构造函数中重复代码,但是您必须重复 m 参数的默认值:

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

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) {}
恬淡成诗 2024-10-26 11:35:34

只是有一点点进步,但是……

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    
    }
}

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    
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文