问题描述
- C#新手在密封类和密封方法处求解
- //程序清单P7_6.csusing System;namespace P7_6{ class Program { static void Main() { BankCard[] cards = new BankCard[] { new BankCard(""001""8888"") new CreditCard(""002""8888"") new CreditCard(""003""8888"")}; foreach (BankCard c in cards) { c.Withdraw(2000); //c.Query(); } ((CreditCard)cards[1]).Query(); ((CreditCard)cards[2]).Query(); } } public abstract class Account { protected string id; protected decimal money; public Account(string id decimal money = 0) { this.id = id; this.money = money; } public abstract void Deposit(decimal x); public abstract bool Withdraw(decimal x); public virtual void Query() { Console.WriteLine(""账号{0}: 余额{1}"" id money); } } public class BankCard : Account { protected string password; public BankCard(string id string password decimal money = 0) : base(id money) { this.password = password; } public override void Deposit(decimal x) { money += x; } public override bool Withdraw(decimal x) { Console.Write(""请输入密码: ""); if (Console.ReadLine() != password) { Console.WriteLine(""密码错误""); return false; } if (money < x) { Console.WriteLine(""卡{0}余额不足"" id); return false; } money -= x; return true; } public sealed override void Query() { Console.Write(""请输入密码: ""); if (Console.ReadLine() != password) { Console.WriteLine(""密码错误""); return; } Console.WriteLine(""账号{0}: 余额{1}"" id money); } } public class CreditCard : BankCard { private decimal limit; public CreditCard(string id string password decimal limit = 5000) : base(id password 0) { this.limit = limit; } public new void Query() { Console.WriteLine(""剩余额度{0}"" limit + money); } public override bool Withdraw(decimal x) { if (x - money > limit) { Console.WriteLine(""卡{0}额度不足"" id); return false; } money -= x; return true; } }}代码如上所示,Bankcard类中密封了方法Query,但是在CreditCard中隐蔽该方法,在前面foreach语句中,第二,第三个CreditCard中都用的是Bankcard类中密封的方法Query,CreditCard不是对它重写了吗?还是foreach语句把其中的元素都认为的是Bankcard类
解决方案
sealed封闭的方法,没办法再在派生类中重写了,你用了new那么按照派生类类型调用,调用的是派生类的方法,用基类类型,调用的是基类的方法。foreach (BankCard c in cards)因为c是bankcard类型,所以不会调用CreditCard的Withdraw/Query如果你想调用,需要先转换:if (c is CreditCard) (c as CreditCard).Query();
解决方案二:
C#密封类、密封方法
C# 密封类和密封方法
时间: 2025-01-23 20:31:19