Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách khai báo và sử dụng Interface trong C#

Interface định nghĩa các property, method, event (các thành viên). Interface chỉ chứa khai báo, lớp dẫn xuất (deriving class) chịu trách nhiệm triển khai (implement).

Khai báo interface:

public interface ITransactions
{
    void ShowTransaction();
    double GetAmount();
}

Ví dụ hoàn chỉnh

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

namespace InterfaceApplication
{
    public interface ITransactions
    {
        void ShowTransaction();
        double GetAmount();
    }
    
    public class Transaction : ITransactions
    {
        private string tCode;
        private string date;
        private double amount;
        
        public Transaction() { tCode = ""; date = ""; amount = 0.0; }
        public Transaction(string c, string d, double a) { tCode = c; date = d; amount = a; }
        
        public double GetAmount() { return amount; }
        
        public void ShowTransaction()
        {
            Console.WriteLine("Transaction: {0}", tCode);
            Console.WriteLine("Date: {0}", date);
            Console.WriteLine("Amount: {0}", GetAmount());
        }
    }
    
    class Tester
    {
        static void Main(string[] args)
        {
            Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
            Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
            t1.ShowTransaction();
            t2.ShowTransaction();
            Console.ReadKey();
        }
    }
}

Kết quả

Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

Lợi ích: Đa hình (polymorphism), tách interface khỏi implementation, cho phép multiple implementation, testing dễ dàng (mock).