亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C# - 接口

接口被定义为所有继承该接口的类都应遵循的语法契约。接口定义了'what' 句法契约的一部分和派生类定义了'how' 句法契约的一部分。

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

抽象类在一定程度上起到了相同的作用,但是,它们主要用于基类只声明少数方法并且派生类实现功能的情况。

声明接口

接口是使用 interface 关键字声明的。它类似于类声明。默认情况下,接口语句是公共的。以下是接口声明的示例 -

public interface ITransactions {
   // interface members
   void showTransaction();
   double getAmount();
}

示例

以下示例演示了上述接口的实现 -

现场演示
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;

namespace InterfaceApplication {
   
   public interface ITransactions {
      // interface members
      void showTransaction();
      double getAmount();
   }
   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 double getAmount() {
         return amount;
      }
      public void showTransaction() {
         Console.WriteLine("Transaction: {0}", tCode);
         Console.WriteLine("Date: {0}", date);
         Console.WriteLine("Amount: {0}", getAmount());
      }
   }
   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();
         Console.ReadKey();
      }
   }
}

当上面的代码编译并执行时,它会产生以下结果 -

Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

C语言

  1. 命令行界面
  2. C#接口
  3. Java 接口
  4. Java 集合框架
  5. Java 集合接口
  6. Java 队列接口
  7. Java NavigableSet 接口
  8. Java Lambda 表达式
  9. 无线车道传感器接口
  10. Java - 接口
  11. C++ 中的接口(抽象类)
  12. Java 9 - 私有接口方法