【问题标题】:C# derived class constructor [closed]C#派生类构造函数[关闭]
【发布时间】:2018-07-11 11:16:15
【问题描述】:

我正在使用视频教程来尝试学习 C#;我认为它误导了我。我哪里错了?

namespace BankAcct
{
    class Acct
    {
        private decimal balance;
        private string acctnum;

        // two constructor methods
        public Acct()
        {
            acctnum = "";
            balance = 0;
        }

        public Acct(string anum, decimal bal)
        {
            acctnum = anum;
            bal = balance;
        }
    } // end of Acct class

    // derived classes
    class CheckingAcct : Acct
    {
        // constructor
        public CheckingAcct(string anum, decimal bal) : base(acctnum, balance)
        {
            balance = bal;
            acctnum = anum;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Acct asacct = new Acct("666", 23.23);
            Console.ReadKey();
        }
    }
}

我正在使用 Visual Studio 社区。当它试图调用派生类中的构造函数时,它会爆炸;关于无法访问私有数据成员的一些事情。我尝试将数据项公开,但无济于事。

【问题讨论】:

  • “它爆炸了”和“某事关于”不是表达错误的好方法。请在您的问题中引用 precise 错误消息(并指出这是一个编译错误,我相信在这种情况下是这样)。您可以从 Visual Studio 复制/粘贴它。但从根本上说,您不需要 CheckingAcct 构造函数中的那些无效赋值 - 您已经链接到 Acct 构造函数,该构造函数正在分配给从参数中获取值的字段。
  • (我也强烈建议使用Account 而不是Acct,以及更完整的参数名称。如果视频给出了这些缩写名称,这可能表明值得尝试查找一个不同的...缩写有时有它们的位置,但绝对不是在这里。)
  • 您不能从派生类写入私有变量。
  • @MongZhu 这不是对保护级别的误解,而是对构造函数链接的误解。呃……其实两者都有。

标签: c# visual-studio


【解决方案1】:

您不能使用在构造函数中设置的变量来调用基本构造函数。 像这样称呼它:

//constructor
public CheckingAcct(string anum, decimal bal) : base(anum, bal)
{
}

【讨论】:

    【解决方案2】:

    一些建议

        ...
    
        //DONE: better chain constructor then copy + paste
        // this("", 0) means Acct("", 0) i.e. acctnum = "" and balance = 0
        public Acct()
          : this("", 0) {
        }
    
        // This constructor assigns acctnum and balance fields 
        public Acct(string anum, decimal bal) {
          acctnum = anum;
          balance = bal; //DONE: Typo amended
        }
    
        ...
    
        //DONE: constructor chain is enough here: 
        //base class constructor - base(acctnum, balance) -
        // will assign acctnum and balance fields for you
        public CheckingAcct(string anum, decimal bal) 
          : base(anum, bal) {
          //DONE: you can't address private balance and acctnum fields there
        }
    

    【讨论】:

    • 我以后会尽量讲清楚。这是我关于 SO 的第一篇文章。经过长时间的中断后,我才重新开始编码。事实证明,昨晚我能够通过将“私有”变量更改为“受保护”来解决,我现在知道使用关键字“构造函数链接”来寻求帮助。谢谢大家的回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2023-04-07
    • 2015-08-18
    • 2023-04-10
    • 1970-01-01
    • 2021-08-29
    • 2016-07-19
    相关资源
    最近更新 更多