Interface định nghĩa property, method, event (các thành viên). Interface chỉ chứa khai báo, lớp dẫn xuất chịu trách nhiệm triển khai. Giúp cung cấp cấu trúc chuẩn cho các class triển khai.
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 Demo
{
public interface ITransactions
{
void ShowTransaction();
}
public class Transaction : ITransactions
{
private string tCode;
private string date;
public Transaction() { tCode = ""; date = ""; }
public Transaction(string c, string d) { tCode = c; date = d; }
public void ShowTransaction()
{
Console.WriteLine("Transaction ID: {0}", tCode);
Console.WriteLine("Date: {0}", date);
}
}
class Tester
{
static void Main(string[] args)
{
Transaction t1 = new Transaction("8877", "6/25/2018");
Transaction t2 = new Transaction("5656", "7/25/2018");
t1.ShowTransaction();
t2.ShowTransaction();
Console.ReadKey();
}
}
}
Kết quả
Transaction ID: 8877
Date: 6/25/2018
Transaction ID: 5656
Date: 7/25/2018
Tính năng mới (C# 8+):
- Default interface methods: Có body trong interface.
- Static members: Static method/field trong interface.
- Private members: Helper method private trong interface.