【问题标题】:Can I call both this and base overloads in a constructor?我可以在构造函数中同时调用 this 和 base 重载吗?
【发布时间】:2016-03-21 15:54:02
【问题描述】:

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

假设我们有以下场景:

    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 的第一个构造函数重载,然后再调用基础构造函数。不过好像不行。

这里的方法是什么?

【问题讨论】:

    标签: c# constructor constructor-overloading


    【解决方案1】:

    正确的做法是

    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( 将相同的字符串传递给两个参数。然后删除单参数构造函数的主体,因为所有工作都在双参数构造函数中完成。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 2011-07-02
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多