C#学习之接口

发表于:2010-9-16 10:19

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

class GoldAccount : IBankAccount
{
    private decimal balance;

    public decimal Balance
    {
        get
        {
            return balance;
        }
    }

    public void PayIn(decimal amount)
    {
        balance += amount;
    }

    public bool Withdraw(decimal amount)
    {
        if (balance >= amount)
        {
            balance -= amount;
            return true;
        }
        Console.WriteLine("Withdraw failed.");
        return false;
    }

    public override string ToString()
    {
        return String.Format("Jupiter Bank Saver:Balance={0,6:C}", balance);
    }
}

  可见,这两个实现类多继承了IBankAccount接口,因此它们必须要实现接口中的所有声明的方法。要不然,编译就会出错。让我们来测试一下,下面是测试代码:

static void Main(string[] args)
{
    IBankAccount venusAccount = new SaverAccount();
    IBankAccount jupiterAccount = new CurrentAccount();
    venusAccount.PayIn(200);
    jupiterAccount.PayIn(500);
    Console.WriteLine(venusAccount.ToString());
    jupiterAccount.PayIn(400);
    jupiterAccount.Withdraw(500);
    jupiterAccount.Withdraw(100);
    Console.WriteLine(jupiterAccount.ToString());

}

  请注意开头两句,我们把它们声明为IBankAccount引用的方式,而没有声明为类的引用,为什么呢?因为,这样我们就可以让它指向执行这个接口的任何类的实例了,比较灵活。但这也有个缺点,如果我们要执行不属于接口的方法,比如这里重载的ToString()方法,就要先把接口的引用强制转换成合适的类型了。

  接口的继承

  接口也可以彼此继承,就象类的继承一样。比如我们又声明一个接口ITransferBankAccount,它继承于IBankAccount接口。

interface ITransferBankAccount : IBankAccount
{
    bool TransferTo(IBankAccount destination, decimal amount);
}

32/3<123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号