C# 中的接口

csharpprogrammingserver side programming更新于 2025/7/13 7:22:17

接口定义属性、方法和事件,它们是接口的成员。接口仅包含成员的声明。定义成员是派生类的责任。这通常有助于提供派生类应遵循的标准结构。

让我们看看如何在 C# 中使用接口成员 − 声明接口

public interface ITransactions {
   // 接口成员
   void showTransaction();
   double getAmount();
}

以下示例展示了如何在 C# 中使用接口 −

示例

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

namespace Demo {

   公共接口 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

相关文章