c#使用介面–協助你更好的理解介面

來源:互聯網
上載者:User
 

前言:這是一篇介紹關於介面使用的隨筆,你要問我介面是何物,那請你親自查一下,這裡只是介紹了簡單有趣的例子,為了讓你更快的接受介面的概念。

本文:這個例子建立在銀行賬戶的基礎上,這個介面包含一個存款和取款的方法,以及一個返回餘額的屬性。為了簡單,我把這個介面和待會兒測試的兩個銀行類放在了一個項目裡,在實際中,銀行類應該放在不同銀行的不同機器裡,這就涉及到remoting技術,這裡暫不討論。下面我們就開始吧!

1、建立工程:c# 控制台應用程式,名字我們叫做ITest;然後項工程中添加一個介面類:IBankAccount代碼如下:

 

IBankAccount
using System;
using System.Collections.Generic;
using System.Text;

namespace ITest
{
    interface IBankAccount
    {
        void PayIn(decimal amount);//存入金額
        bool WithDraw(decimal amount);//取出金額
        decimal Balance//剩餘金額
        {
            get;
        }
    }
}

 

然後,我們就可以開始為不同的銀行編寫不同的類了,下面是銀行1的類Bank1:代碼很簡單,我就不做注釋了

 

Bank1
namespace ITest
{
    class Bank1: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("Bank1餘額不足");
                return false;
            }
        }
        public decimal Balance
        {
            get
            {
                return balance;
            }
        }
        public override string ToString()
        {
            return string.Format("Bank1儲戶的餘額為:{0}", balance);
        }
    }
}

 

然後添加銀行2的類,代碼同上,只是細節地方改一下把Bank1改稱Bank2即可。

2、最後在主要代碼中,使用介面和類:

 

Program.cs
namespace ITest
{
    class Program
    {
        static void Main(string[] args)
        {
            IBankAccount bankone = new Bank1();
            IBankAccount banktwo = new Bank2();
            bankone.PayIn(200);//往bank1裡存入200
            bankone.WithDraw(50);//從bank1裡提取50
            Console.WriteLine(bankone.ToString());//輸出餘額

            banktwo.PayIn(300);
            banktwo.WithDraw(305);
            Console.WriteLine(banktwo.ToString());
            Console.ReadKey();
        }
    }
}

 

至此,整個介面就完成了,你只需調適即可。效果如下:

電腦在交流中得到發展,所以有了互連網。技術在交流中成長,所以有了cnblog!請不要吝嗇自己的才華,盡情的與我們分享吧!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.