6.接口

声明接口在语法上与声明抽象类完全相同,但不允许提供接口中任何成员的实现方式。 一般情况下,接口只能包含方法、属性、索引器和事件的声明。不能实例化接口 ,它只能包含其成员的 签名。接口既不能有构造函数,接口定义也不允许包含运算符重载。

6.1 定义和实现接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 定义接口
{
    public interface IBankAccount
    {
        void PayIn(decimal amount);
        bool Withdraw(decimal amount);
        decimal Balance
        { get; }



    }

    class Program
    {
        static void Main(string[] args)
        {
            IBankAccount x = new SaveAccount();
            IBankAccount y = new SaveAccount();
            x.PayIn(200);
            x.Withdraw(100);
            Console.WriteLine(x.ToString());
            y.PayIn(500);
            y.Withdraw(600);
            y.Withdraw(100);
            Console.WriteLine(y.ToString());

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 定义接口
{
    public class SaveAccount : IBankAccount
    {
        private decimal balance;
        public void PayIn(decimal amount)
        {
             balance+= amount;
        }
        public bool Withdraw(decimal amount)
        {
            if (balance >= amount)
            {
                balance -= amount;
                return true;

            }
            else
            {
                Console.WriteLine("Withdraw1 attempt failed");
                return false;
            }

        }
        public decimal Balance
        {
            get
            {
                return balance;

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


    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 定义接口
{
    public class GoldAccount : IBankAccount
    {
        private decimal balance;
        public void PayIn(decimal amount)
        {
            balance += amount;
        }
        public bool Withdraw(decimal amount)
        {
            if (balance >= amount)
            {
                balance -= amount;
                return true;

            }
            else
            {
                Console.WriteLine("Withdraw1 attempt failed");
                return false;
            }

        }
        public decimal Balance
        {
            get
            {
                return balance;

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


    }
}
定义接口

转载于:https://www.cnblogs.com/sharp-c/archive/2012/09/09/2678099.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值