0

我能找到的最接近的线程是这个,但是场景不同——要调用的基本构造函数是默认的。这里我需要指定我要传递的参数。

假设我们有以下场景:

    public class Base
    {
        public string Str;

        public Base(string s)
        {
            Str = s;
        }
    }

    public class A : Base
    {
        public string Str2;

        public A(string str2)
            : base(str2)
        {
            Str2 = str2;
        }

        public A(string str2, string str)
            : base(str)
        {
            Str2 = str2;
        }
    }

我想避免在 A 的第二个构造函数重载中重复相同的逻辑(从技术上讲,我可以将所有逻辑包装到一个函数中,以减少复制粘贴/提高可维护性,因为最后所有重载都将依赖于相同的代码。如果没有其他解决方案)。

我以为我可以先调用 A 的第一个构造函数重载,然后再调用基础构造函数。但似乎我做不到。

这里的方法是什么?

4

1 回答 1

2

正确的方法是

public class A : Base
{
    public string Str2;

    public A(string str2)
        : this(str2, str2)
    {
    }

    public A(string str2, string str)
        : base(str)
    {
        Str2 = str2;
    }
}

的单参数构造函数A调用将A相同字符串传递给两个参数的 2 参数构造函数,使用this(而不是base(。然后删除单参数构造函数的主体,因为所有工作都在双参数构造函数中完成。

于 2016-03-21T16:02:56.943 回答