อินเทอร์เฟซกำหนดคุณสมบัติ เมธอด และเหตุการณ์ ซึ่งเป็นสมาชิกของอินเทอร์เฟซ อินเทอร์เฟซประกอบด้วยการประกาศของสมาชิกเท่านั้น เป็นความรับผิดชอบของคลาสที่ได้รับในการกำหนดสมาชิก มักจะช่วยในการจัดเตรียมโครงสร้างมาตรฐานที่คลาสที่ได้รับตามมา
ให้เราดูวิธีการประกาศส่วนต่อประสานใน C# กับสมาชิกส่วนต่อประสาน -
public interface InterfaceName {
// interface members
} ต่อไปนี้เป็นตัวอย่างที่แสดงวิธีการใช้อินเทอร์เฟซใน C# -
ตัวอย่าง
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace Demo {
public interface ITransactions {
// interface members
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();
}
}
}