为什么不能在C#中继承类?
为什么不能在C#中继承类?
这个问题已经有了答案:
我试图创建一个基本的银行系统来练习使用类,在创建父类“帐户”之后,我尝试创建一个“储蓄”类,该类将成为子类并继承属性和方法,但是,无论我查找什么都不会告诉我如何做到这一点。我会得到诸如“必须声明一个主体,因为它未标记为抽象、外部或部分”等错误。我真的不知道该怎么做才能让它工作,所以我希望这里有人能帮助我,以下是我的代码:
public class Account { protected string name; protected string birthdate; protected string address; protected double balance; protected string status; protected string type; public Account(string customerName, string customerBirthdate, string customerAddress, int customerBalance) { name = customerName; birthdate = customerBirthdate; address = customerAddress; balance = customerBalance; status = "Ok"; type = "Basic"; } public void customerDetails() { Console.WriteLine("Name: {0}, Birthdate: {1}, Address: {2}", name, birthdate, address); } public void accountDetails() { Console.WriteLine("Balance: £{0}, Account Status: {1}, Account Type: {2}", Math.Round(balance, 2), status, type); } private void updateStatus() { if (balance < 0) { status = "Overdrawn"; } else if (balance > 0 ) { status = "Ok"; } } public void deposit(int amount) { balance += amount; updateStatus(); } public void withdraw(int amount) { balance -= amount; updateStatus(); } } public class Savings : Account { public Savings(string customerName, string customerBirthdate, string customerAddress, int customerBalance) : Account(customerName, customerBirthdate, customerAddress, customerBalance) { name = customerName; birthdate = customerBirthdate; address = customerAddress; balance = customerBalance; status = "Ok"; type = "Basic"; } }
如果有人能帮忙,提前感谢!
admin 更改状态以发布 2023年5月22日
代码应该像这样(基于账户改变)
public class Account { protected string name; protected string birthdate; protected string address; protected double balance; protected string status; protected string type; public Account(string customerName, string customerBirthdate, string customerAddress, int customerBalance) { this.name = customerName; this.birthdate = customerBirthdate; this.address = customerAddress; this.balance = customerBalance; this.status = "Ok"; this.type = "Basic"; } public void customerDetails() { Console.WriteLine("Name: {0}, Birthdate: {1}, Address: {2}", name, birthdate, address); } public void accountDetails() { Console.WriteLine("Balance: £{0}, Account Status: {1}, Account Type: {2}", Math.Round(balance, 2), status, type); } private void updateStatus() { if (balance < 0) { status = "Overdrawn"; } else if (balance > 0) { status = "Ok"; } } public void deposit(int amount) { balance += amount; updateStatus(); } public void withdraw(int amount) { balance -= amount; updateStatus(); } } public class Savings : Account { public Savings(string customerName, string customerBirthdate, string customerAddress, int customerBalance) : base (customerName, customerBirthdate, customerAddress, customerBalance) { base.name = customerName; base.birthdate = customerBirthdate; base.address = customerAddress; base.balance = customerBalance; base.status = "Ok"; base.type = "Basic"; } }