如何在 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