首页  >  文章  >  后端开发  >  C# 接口

C# 接口

PHPz
PHPz原创
2024-09-03 15:30:00515浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
上一篇:C# Delegates下一篇:Timer in C#