C# 基础入门 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

接口


  接口定义了所有类继承接口时应遵循的语法合同。接口定义了语法合同 "是什么" 部分,派生类定义了语法合同 "怎么做" 部分。

  接口定义了属性、方法和事件,这些都是接口的成员。接口只包含了成员的声明。成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。

  接口使用 interface 关键字声明,它与类的声明类似。接口声明默认是 public 的。 接口的继承在声明类时,在类名称后放置一个冒号(:),然后在冒号后指定要从中继承的接口,继承多个接口用逗号(,)隔开。

interface IEquatable
{
    public void print();
}

  看下面接口的具体实现

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

namespace InterfaceApplication
{
   public interface ITransactions   //定义接口
   {
      // 接口成员
      void showTransaction();
   }

   public class Transaction : ITransactions // 类继承接口
   {
      private string tCode;
      private string date;
      private double amount;
      public Transaction()
      {
         tCode = " ";
         date = " ";
         amount = 0.0;
      }

      public Transaction(string c, string d, double a)
      {
         tCode = c;
         date = d;
         amount = a;
      }

      public void showTransaction()   // 接口中的方法具体实现
      {
         Console.WriteLine("Transaction: {0}", tCode);
         Console.WriteLine("Date: {0}", date);
         Console.WriteLine("Amount: {0}", amount);
      }

   }

   class Tester
   {
      static void Main(string[] args)
      {
         Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
         Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
         t1.showTransaction();  //方法的调用
         t2.showTransaction();
      }
   }
}