C# 介面

PHPz
發布: 2024-09-03 15:30:00
原創
255 人瀏覽過

Interface,在C#中是一個關鍵字,它包含一組抽象方法和屬性,這些方法和屬性由抽像或非抽象類別實作或使用。定義方法是介面內的屬性,預設情況下它們是公共和抽象的。

用最簡單的話來說,介面就像一個契約,主體中包含的每個成員或元件都必須遵循契約,它定義了必須做什麼。該介面不包含任何字段,並且始終透過使用關鍵字“interface”來定義。

文法:

語法以介面關鍵字開頭,後面跟著介面名稱,然後是正文。

interface <name_for_interface>
{
//abstract methods
//abstract properties.
}
登入後複製

如您所見,我們有 C# 中介面的標準語法,它以「interface」關鍵字開頭,然後是介面的名稱,然後是主體內的抽象方法和屬性。在 C# 中,可以在類別或結構內部實作和使用多個介面。這些介面可以將各種方法、索引器、屬性以及事件作為成員。

為什麼我們需要 C# 介面?

基本上我們已經明白介面內部沒有特定的功能,如果是這樣,那我們為什麼需要介面?

什麼時候使用介面?

  • 安全性: 當我們必須簡單地隱藏某些功能並稍後使用它們時。有必要隱藏一些細節,同時只顯示對使用者重要的細節。
  • 多重繼承:在c#中,一個類別可以繼承一個簡單的父類,繼承其所有功能。 C# 不支援多重繼承,原因很簡單,就是為了不讓 C# 變得複雜。但是透過使用接口,可以將多個接口實現到單一類別。

C# 介面通常包含以下元素:

  1. 宣告 – 在 C# 中,介面是定義一組方法簽章、屬性、事件或索引器的契約。它不包含任何實現,而是作為類別要遵循的藍圖。實作介面的類別必須為介面中聲明的所有成員提供具體的實作。
  2. 成員 – 介面成員是介面內宣告的方法、屬性、事件和索引器。他們定義了實現類別必須遵守的契約,以確保不同類別之間行為一致。實現類別必須為這些成員提供具體的實現,促進程式碼一致性,並實現多態性和程式碼重複使用。
  3. 實作 – 實作介面的類別必須為介面中宣告的所有成員提供實作。該類別可以使用 :interfaceName 語法明確指定它實作一個介面。例如:
    public class MyClass : IMyInterface
    {
    public void Method1()
    {
    // Method implementation
    }public string Property1 { get; set; }
    
    public event EventHandler Event1;
    }
    登入後複製
  4. 多重繼承:C# 透過介面支援多重繼承。一個類別可以實現多個接口,從而允許它繼承多組方法簽名,而無需與實現的多重繼承相關的複雜性。這使得設計類別具有更大的靈活性,同時避免了傳統多重繼承中固有的鑽石問題。
  5. 介面繼承:在 C# 中,介面繼承允許派生介面繼承一個或多個基底介面中定義的方法簽章。實作派生介面的類別必須提供所有繼承方法的實作。這使得能夠創建介面層次結構,促進程式碼重用和物件設計的靈活性。

C# 介面範例

現在我們已經了解了什麼是介面及其需求。讓我們示範一個帶有介面實現的 C# 程式碼的簡單範例。

範例#1

程式實作介面並列印一條簡單的語句。

代碼:

using System;
namespace MyApplication {
interface SampleInterface {
void InterfaceMethod();
}
class Int_Example : SampleInterface
{
public void InterfaceMethod() {
Console.WriteLine("\nThis is simple example of Interface in C#.");
}
}
class Program {
static void Main(string[] args) {
Int_Example myInterface = new Int_Example();
myInterface.InterfaceMethod();
Console.Read();
}
}
}
登入後複製

程式碼解釋:從使用和命名空間開始,產生一個基本介面作為 SampleInterface,其主體中有一個方法。介面內的該方法沒有任何特定的主體。然後我們有新的類別來實作我們創建的介面。使用 class 關鍵字創建,後面跟著類別名,然後使用冒號符號後面跟著介面名稱來實作介面。在我們的 Int_Example 類別中,我們有先前建立的介面方法,當時它還沒有實體,現在我們加入了簡單的列印語句,它說:「這是 C# 中介面的簡單範例。」

Then begins our mail class, namely Program, with the static void main statement. Inside our main class, we have created a new object for our Int_Example class which inherits interface. The new object is created and to the next line, our method created earlier is called up. Finally, our newly created object will call the earlier created method and the body inside that method will be executed here. With Console.Read(); the program will wait for user input before exiting.

Output:

C# 介面

Upon successful compilation and execution, the program must simply print the statement: “This is a simple example of Interface in C#.”

Example #2

Arithmetic operations using the interface.

Code:

using System;
namespace arth_interface {
public interface SampleInterface {
void sam_add(int a, int b);
void sam_sub(int a, int b);
void display();
}
class interface_class : SampleInterface {
int x, y;
public void sam_add(int a, int b) {
int m, n;
m = a;
n = b;
x = m + n;
}
public void sam_sub(int a, int b) {
int m, n;
m = a;
n = b;
y = a - b;
}
public void display() {
Console.WriteLine("Added Value is:" + x);
Console.WriteLine("Subtracted value is:" + y);
}
}
class arth_interface {
static void Main(string[] args) {
interface_class obj_interface_class = new interface_class();
int fnumber, snumber;
Console.WriteLine("Please Enter 1st Number to perform Addition and Subtraction:");
fnumber = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Now 2nd Number to perform Addition and Subtraction:");
snumber = Convert.ToInt16(Console.ReadLine());
obj_interface_class.sam_add(fnumber, snumber);
obj_interface_class.sam_sub(fnumber, snumber);
obj_interface_class.display();
Console.ReadKey();
}
}
}
登入後複製

Code Interpretation: Similar to our first example, we have used and namespace statements, followed by the interface and its body with methods. We have two basic methods for addition and subtraction with void as return type, two integers inside every method, respectively. Next, we have our class which implements our interface.

We’ve declared two integers and then we have our first method to calculate addition. Here is the operation that needs to be done for addition and the same is for the subtraction. Then we have our display method, which consists of two print statements, printing addition and subtraction values of the numbers passed.

Finally, we have our class with the main method, where we initially created an object for our interface. Then the program prints “Please Enter the 1st Number to perform Addition and Subtraction:”, where the user inputs a first number and the later second number, for the purpose of calculations. With the object created earlier, the program calls the add and sub-methods from the interface and the same operations are done. At last, we have our display method, which displays our results as defined in the display method and ReadKey(); method holds up our program until any key is pressed.

Output:

C# 介面

Advantages

Below are some of the advantages given.

  • One of the major advantages of Interface in C# is a better alternative to implement multiple inheritances.
  • The interface enables the plug-and-play method.
  • Complete Abstraction can be achieved by the implementation of Interface.
  • Along with making our code easy to maintain, concept loose coupling can be achieved.

Conclusion

We have understood what Interface in C# is. The proper syntax for an interface along with an explanation. To wrap it up, Interfaces in C# are a way to fill the emptiness of multiple inheritances in the language. Later we learned why do we actually need the interface in C# followed by the examples to demonstrate the understanding of the interfaces. The first example was to demonstrate simple use of interface while with the second example we implemented arithmetic operations, followed by Code Interpretation and output screenshot.

以上是C# 介面的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!