C# 接口
提示
- 接口的定义和特性:在C#中,接口是一组完全抽象的方法(无主体),使用
interface
关键字定义。接口中的成员默认公共,无字段,通常以"I"开头命名,强调代码抽象和规范。 - 接口的实现和多重继承:类通过
:
符号实现接口,必须定义接口中的所有方法。一个类可以实现多个接口,允许C#中的多重继承,提高灵活性和功能丰富性。 - 接口引用变量和实际应用:可以使用接口类型的引用变量指向实现了该接口的类对象,增加代码的松耦合性。接口在实现类特定行为规范时发挥重要作用,如不同多边形计算面积的规则。
在 C# 中,接口类似于抽象类。然而,与抽象类不同的是,接口中的所有方法都是完全抽象的(没有主体的方法)。
我们使用 interface
关键字来创建接口。例如,
interface IPolygon {
// 没有主体的方法
void calculateArea();
}
这里,
IPolygon
是接口的名称。- 按照惯例,接口以 I 开头,这样我们可以仅凭其名称就识别它。
- 在接口内不能使用访问修饰符。
- 接口的所有成员默认都是公共的。
- 接口不允许有字段。
实现接口
我们不能创建接口的对象。要使用接口,其他类必须实现它。与 C# 继承 中相同,我们使用 :
符号来实现接口。例如,
using System;
namespace CsharpInterface {
interface IPolygon {
// 没有主体的方法
void calculateArea(int l, int b);
}
class Rectangle : IPolygon {
// 实现接口内的方法
public void calculateArea(int l, int b) {
int area = l * b;
Console.WriteLine("矩形的面积: " + area);
}
}
class Program {
static void Main (string [] args) {
Rectangle r1 = new Rectangle();
r1.calculateArea(100, 200);
}
}
}
输出
矩形的面积: 20000
在上述示例中,我们创建了一个名为 IPolygon
的接口。该接口包含一个没有实现的方法 calculateArea(int a, int b)
。
这里,Rectangle
类实现了 IPolygon
。并提供了 calculateArea(int a, int b)
方法的实现。
注意:我们必须在实现它的类中提供接口的所有方法的实现。
实现多个接口
不同于继承,一个类可以实现多个接口。例如,
using System;
namespace CsharpInterface {
interface IPolygon {
// 没有主体的方法
void calculateArea(int a, int b);
}
interface IColor {
void getColor();
}
// 实现两个接口
class Rectangle : IPolygon, IColor {
// 实现 IPolygon 接口
public void calculateArea(int a, int b) {
int area = a * b;
Console.WriteLine("矩形的面积: " + area);
}
// 实现 IColor 接口
public void getColor() {
Console.WriteLine("红色矩形");
}
}
class Program {
static void Main (string [] args) {
Rectangle r1 = new Rectangle();
r1.calculateArea(100, 200);
r1.getColor();
}
}
}
输出
矩形的面积: 20000
红色矩形
在上述示例中,我们有两个接口,IPolygon
和 IColor
。
class Rectangle : IPolygon, IColor {
…
}
我们在 Rectangle
类中实现了这两个接口,用 ,
分隔。
现在,Rectangle
必须实现这两个接口的方法。
使用接口的引用变量
我们可以使用接口的引用变量。例如,
using System;
namespace CsharpInterface {
interface IPolygon {
// 没有实现体的方法
void calculateArea(int l, int b);
}
class Rectangle : IPolygon {
// 接口内方法的实现
public void calculateArea(int l, int b) {
int area = l * b;
Console.WriteLine("矩形的面积: " + area);
}
}
class Program {
static void Main (string [] args) {
// 使用接口的引用变量
IPolygon r1 = new Rectangle();
r1.calculateArea(100, 200);
}
}
}
输出
矩形的面积: 20000
在上述示例中,我们创建了一个名为 IPolygon
的接口。该接口包含一个没有实现体的方法 calculateArea(int l, int b)
。
IPolygon r1 = new Rectangle();
注意,我们使用了接口 IPolygon
的引用变量。它指向实现了该接口的类 Rectangle
。
尽管我们不能创建接口的对象,但我们仍然可以使用指向其实现类的接口的引用变量。