C# 中的接口是什么?

csharpprogrammingserver side programming更新于 2025/10/13 19:52:17

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

让我们看看如何在 C# 中声明带有接口成员 − 的接口

public interface InterfaceName {
    // 接口成员
}

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

示例

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();
      }
   }
}

相关文章