- 接口是允许多重继承的引用类型。
- 在接口中只能声明“抽象”成员,因此接口不能直接实例化。
- 接口可以包含方法、属性、事件和索引器等成员。
- 通常在接口名称的开头使用字母“I”(尽管这不是必需的并且可以以其他方式声明)。
- 接口中成员的访问权限默认是public的,因此在定义接口时不需要指定接口成员的访问修饰符。如果不指定,编译器会报错。
- 声明接口成员时,不能为接口成员编写具体的可执行代码,只要在定义成员时指定成员的名称和参数即可。
- 当实现接口(由类继承)时,派生类必须实现接口中的所有成员,除非派生类本身是抽象类。
声明一个接口
要在 C# 中声明接口,必须使用 interface 关键字。语法结构是:
public interface InterfaceName{
returnType funcName1(type parameterList);
returnType funcName2(type parameterList);
… …
}
其中InterfaceName是接口名称,returnType是返回类型,funcName是成员函数名称,parameterList是参数列表。
【示例】 下面通过一个具体的例子来说明如何使用该接口。
use system;
namespace it-kiso.com
{
public interface Iwebsite{
void setValue(string str1, string str2);
void disPlay();
}
public class Website : Iwebsite{
public string name, url;
public void setValue(string n, string u){
name = n;
url = u;
}
public void disPlay(){
Console.WriteLine("{0} {1}", name, url);
}
}
class Demo
{
static void Main(string[] args)
{
Website web = new Website();
web.setValue("IT基礎", "https://it-kiso.com");
web.disPlay();
}
}
} 操作的结果将是:
IT基礎 https://it-kiso.com
接口继承
在 C# 中,一个接口可以继承另一个接口。例如,您可以使用接口1继承接口2。如果使用类来实现接口 1,则必须同时实现接口 1 和接口 2 的所有成员。例如:
using System;
namespace it-kiso.com
{
public interface IParentInterface
{
void ParentInterfaceMethod();
}
public interface IMyInterface : IParentInterface
{
void MethodToImplement();
}
class Demo : IMyInterface
{
static void Main(string[] args)
{
Demo demo = new Demo();
demo.MethodToImplement();
demo.ParentInterfaceMethod();
}
public void MethodToImplement(){
Console.WriteLine("IMyInterface インターフェースの MethodToImplement 関数を実装します");
}
public void ParentInterfaceMethod(){
Console.WriteLine("IParentInterface インターフェースの ParentInterfaceMethod 関数を実装します");
}
}
} 操作的结果将是:
IMyInterface インターフェースの MethodToImplement 関数を実装します
IParentInterface インターフェースの ParentInterfaceMethod 関数を実装します




![2021 年如何设置 Raspberry Pi Web 服务器 [指南]](https://i0.wp.com/pcmanabu.com/wp-content/uploads/2019/10/web-server-02-309x198.png?w=1200&resize=1200,0&ssl=1)

