C# 是一种面向对象的编程语言,提供称为接口的独特功能。它们使您能够声明类必须实现的属性和方法的集合,而无需提及应如何实现它们的具体细节。
能够编写独立于类的实现细节的代码是接口的主要好处之一。任何实现该接口的类的每个对象都可以使用接口引用来引用。
因此,在不同的类实现之间切换更加简单,而无需修改使用该类的代码。
在 C# 中定义接口的语法
在C#中,可以使用interface关键字和接口名称来定义接口。正如下面的示例所示,接口定义可能包括方法、属性、事件和索引器 -
interface <interface_name> {
// declare Events
// declare properties
// declare indexers
// declare methods
}
冒号运算符 - 实现接口的语法包括冒号 (:) 运算符,后跟要实现的接口的名称。
属性-属性是接口中的值
方法- 方法是接口中的函数
示例
在此示例中,我们将使用方法 CalArea() 定义接口 Shape。计算形状的面积。为此,我们将定义一个类 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# 中的接口引用为您的代码提供了强大的机制。您可以使用支持该接口的任何对象创建代码,无论其特定类如何。