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: 376the percentage of the student is: 94
结论最后,c# 中的接口引用为您的代码提供了强大的机制。您可以使用支持该接口的任何对象创建代码,无论其特定类如何。
以上就是如何在c#中使用接口引用?的详细内容。