接口定义属性,方法和事件,它们是接口的成员。接口仅包含成员的声明。定义成员是派生类的责任。它通常有助于提供派生类将遵循的标准结构。
让我们看看如何使用接口成员在C#中声明接口-
public interface ITransactions { //成员 void showTransaction(); double getAmount(); }
以下是显示如何在C#中使用Interface的示例-
using System.Collections.Generic; using System.Linq; using System.Text; using System; 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(); } } }
输出结果
Transaction ID: 8877 Date: 6/25/2018 Transaction ID: 5656 Date: 7/25/2018