C# 接口例题
【摘要】 希望通过此例题可以帮助你更好的理解接口的作用
我们创建一个银行接口,有存钱,取钱方法,还有账号余额属性,,,然后实现这个接口,,,
using System; namespace InterfaceDemo{ /// <summary> /// 定义一个银行接口 /// </summary> interface IBankAccount { /...
希望通过此例题可以帮助你更好的理解接口的作用
我们创建一个银行接口,有存钱,取钱方法,还有账号余额属性,,,然后实现这个接口,,,
-
using System;
-
-
namespace InterfaceDemo
-
{
-
/// <summary>
-
/// 定义一个银行接口
-
/// </summary>
-
interface IBankAccount
-
{
-
//存款
-
void PayIn(decimal amout);
-
//取款
-
bool WithShowMySelf(decimal amout);
-
//属性:账户余额
-
decimal Balance { get; }
-
}
-
/// <summary>
-
/// 银行账户,实现接口
-
/// </summary>
-
class SaverAccount : IBankAccount
-
{
-
private decimal balance; //私有化余额
-
public decimal Balance //只读金钱属性
-
{
-
get
-
{
-
return balance;
-
}
-
}
-
-
public void PayIn(decimal amout) //存钱
-
{
-
balance += amout;
-
}
-
-
public bool WithShowMySelf(decimal amout)//取钱
-
{
-
if(balance >= amout)
-
{
-
balance -= amout;
-
return true;
-
}
-
else
-
{
-
Console.WriteLine("银行余额不足,取款失败");
-
return false;
-
}
-
}
-
}
-
class Program
-
{
-
static void Main(string[] args)
-
{
-
IBankAccount myAccount = new SaverAccount();
-
myAccount.PayIn(1000);
-
myAccount.WithShowMySelf(200);
-
Console.WriteLine("余额:{0}",myAccount.Balance);
-
-
Console.Read();
-
}
-
}
-
}
-
/// <summary>
-
///需要使用转账功能的接口
-
/// </summary>
-
interface ItranBack : IBankAccount
-
{
-
//继承的基础上,添加转账的方法
-
bool TransferTo(IBankAccount destination, decimal amount);
-
}
-
-
class Transfer : ItranBack
-
{
-
private decimal balance; //私有化余额
-
public decimal Balance //只读金钱属性
-
{
-
get
-
{
-
return balance;
-
}
-
}
-
-
public void PayIn(decimal amout) //存钱
-
{
-
balance += amout;
-
}
-
-
/// <summary>
-
/// 转账方法
-
/// </summary>
-
/// <param name="destination">转账的人的账号</param>
-
/// <param name="amount">转账金额</param>
-
/// <returns></returns>
-
public bool TransferTo(IBankAccount destination, decimal amount)
-
{
-
bool result = WithShowMySelf(amount);
-
if(result == true)
-
{
-
destination.PayIn(amount);
-
}
-
return result;
-
}
-
-
public bool WithShowMySelf(decimal amout)//取钱
-
{
-
if (balance >= amout)
-
{
-
balance -= amout;
-
return true;
-
}
-
else
-
{
-
Console.WriteLine("银行余额不足,取款失败");
-
return false;
-
}
-
}
-
}
-
-
class Program
-
{
-
static void Main(string[] args)
-
{
-
//创建两个账号
-
IBankAccount myAccount = new SaverAccount();
-
ItranBack yourAccount = new Transfer();
-
-
//可进行 存钱,取钱,,一系列操作,
-
myAccount.WithShowMySelf(1000);
-
myAccount.PayIn(1000);
-
yourAccount.PayIn(100);
-
-
Console.WriteLine("转账前:我卡里的余额:{0}", myAccount.Balance);
-
Console.WriteLine("转账前:你卡里的余额:{0}", yourAccount.Balance);
-
-
yourAccount.TransferTo(myAccount, 500); //转账
-
-
Console.WriteLine("转账后:我卡里的余额:{0}", myAccount.Balance);
-
Console.WriteLine("转账后:你卡里的余额:{0}", yourAccount.Balance);
-
-
Console.Read();
-
}
-
}
-
}
文章来源: czhenya.blog.csdn.net,作者:陈言必行,版权归原作者所有,如需转载,请联系作者。
原文链接:czhenya.blog.csdn.net/article/details/77870495
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)