plutorong 2021-05-20 16:14 采纳率: 0%
浏览 18

接口的多态化,对重要语句进行注释

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IPayable[] payers = new IPayable[4];
            payers[0] = new BankAccount(3000);
            payers[1] = new BankAccount(5000);
            payers[2] = new CreditCard(5000);
            payers[3] = new DebitCard((BankAccount)payers[1]);
            foreach(IPayable  payer in payers)
            {
                Receive(payer, 1500);
                Receive(payer, 2000);
            }
        }
        static void Receive(IPayable  payer, decimal money)
        {
            if (payer.Pay(money))
                Console.WriteLine("{0}成功付款{1}元", payer, money);
            else
                Console.WriteLine("{0}付款失败", payer);
        }
    }
}   public interface IPayable
    {
    bool Pay(decimal money);
    }
public class BankAccount : IPayable
{
    protected decimal balance = 0;
    public decimal Balance
    {
        get { return balance; }
        set { balance = value; }
    }
    public BankAccount(decimal balance)
    {
        this.balance = balance;
    }
    public virtual bool Pay(decimal money)
    {
        if (balance >= money)
        {
            balance -= money;
            return true;
        }
        else
            return false;
    }
}
public class CreditCard : BankAccount
{
    private decimal credit;
    public decimal Credit
    {
        get { return credit; }
    }
    public CreditCard(decimal credit)
        : base(0)
    {
        this.credit = credit;
    }
    public override bool Pay(decimal money)
    {
        if (money <= credit + balance)
        {
            balance -= money;
            return true;
        }
        else
            return false;
    }
}
 
    public class DebitCard : IPayable
    {
        private BankAccount account;
        public DebitCard(BankAccount account)
        {
            this.account = account;
        }
        public bool Pay(decimal money)
        {
            return account.Pay(money);
        }
    }

  • 写回答

3条回答 默认 最新

  • CSDN专家-sinJack 2021-05-20 16:24
    关注

    就只是子类继承父类,可以使用父类公共的属性和方法而已。

    评论

报告相同问题?

悬赏问题

  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错
  • ¥15 换yum源但仍然用不了httpd
  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal