如何在 C# 中使用介面引用?
C# 是一種面向物件的程式語言,它提供了一種稱為介面的獨特功能。它們使您能夠宣告一個類必須實現的屬性和方法集合,而無需提及如何實現它們的具體細節。
介面的主要優點之一是能夠編寫獨立於類實現細節的程式碼。可以使用介面引用來引用實現該介面的任何類的每個物件。
因此,在不修改使用該類的程式碼的情況下,在不同的類實現之間切換變得更加容易。
在 C# 中定義介面的語法
在 C# 中,您可以使用 interface 關鍵字和介面的名稱來定義介面。如以下示例所示,介面定義可以包含方法、屬性、事件和索引器 -
interface <interface_name> {
// declare Events
// declare properties
// declare indexers
// declare methods
}
冒號運算子 - 實現介面的語法包括一個冒號 (:) 運算子,後跟要實現的介面的名稱。
屬性 - 屬性是介面中的值
方法 - 方法是介面中的函式
示例
在此示例中,我們將定義一個介面 Shape,其中包含一個方法 CalArea()。用於計算形狀的面積。為此,我們將定義一個 Circle 類,該類實現 Shape 介面併為介面使用的方法 CalArea() 提供實現。
演算法
步驟 1 - 在第一步中,使用所需的方法和屬性定義一個介面。在定義介面時,您可以包含屬性、方法、事件和索引器。
步驟 2 - 接下來建立一個實現該介面的類。
步驟 3 - 建立介面型別的一個引用變數。
步驟 4 - 例項化該類並將物件分配給引用變數。
步驟 5 - 最後,使用介面引用來呼叫介面中定義的方法和屬性。
using System;
interface Shape {
double CalArea();
}
class Circle : Shape {
private double radius;
public Circle(double r) {
radius = r;
}
public double GetArea() {
return 3.14 * radius * radius;
}
}
class Program {
static void Main(string[] args) {
Shape shapeRefr;
Circle Obj = new Circle(5);
shapeRefr = Obj;
Console.WriteLine("Area of the circle is " + shapeRefr.CalArea());
}
}
輸出
Area of the circle is 78.5
示例
在此示例中,我們將計算學生的 4 門課程的成績和總成績的百分比。在此示例中,我們將用 2 個方法初始化一個介面。
演算法
步驟 1 - 在第一步中,使用所需的 2 個方法定義一個介面:一個方法用於計算成績,另一個方法用於計算百分比。
步驟 2 - 接下來建立一個實現該介面的類。
步驟 3 - 建立介面型別的一個引用變數。
步驟 4 - 例項化該類並將物件分配給引用變數。
步驟 5 - 最後,使用介面引用來呼叫介面中定義的方法和屬性。
using System;
interface Olevel //create interface {
double marks();
double percentage();
}
class Result : Olevel //create class {
private double Math;
private double Science;
private double English;
private double Computer;
public Result(double math, double science, double english, double computer) {
this.Math = math;
this.Science = science;
this.English = english;
this.Computer = computer;
}
//create methods
public double marks() {
double mrks;
mrks= Math+Science+English+Computer;
return mrks;
}
public double percentage() {
double x= Math+Science+English+Computer;
return (x/400) * 100;
}
}
class Program {
static void Main(string[] args) {
Result result = new Result(90, 95, 93, 98);
// Create an interface reference variable and assign the instance of result class to it
Olevel olev = result;
Console.WriteLine("The Total marks of the student out of 400 are: " + result.marks());
Console.WriteLine("The percentage of the student is: " + result.percentage());
}
}
輸出
The Total marks of the student out of 400 are: 376 The percentage of the student is: 94
結論
最後,C# 中的介面引用為您的程式碼提供了強大的機制。您可以使用支援該介面的任何物件建立程式碼,而不管其具體的類是什麼。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP