C#接口(Interface)
C#中的接口
接口是C#中一种重要的概念,它定义了一组函数成员,但不实现它们。接口提供了一种标准结构,使得实现接口的类或结构在形式上保持一致。接口定义了属性、方法和事件,这些都是接口的成员,但接口只包含成员的声明,具体的实现由派生类负责
定义接口
接口使用interface关键字声明,通常接口名称以大写字母“I”开头。
接口的作用
接口为代码编写和程序开发提供了一个“协定”,即一个规范。使用接口可以确保不同的类实现相同的方法,从而提高代码的可维护性和扩展性。例如,如果有多个类需要实现一个共同的方法,可以通过接口来约束这些类
接口的继承
namespace 接口
{
internal class Program
{
static void Main(string[] args)
{
总结:
1.接口不能使用static
2.接口中的成员不能使用访问修饰符,所有的成员默认都是public,但是public也不能写
3.类或者结构体实现的时候,类的成员相对于接口成员,只能多,不能少
4.如果接口中规定的属性拥有get和set,类中必须都有,如果接口中只有get,类中可以有get和set
5.当类实现多个接口的时候,使用 ,分割
6.当类同时继承和实现接口的时候,必须把基类放在前面
}
}
//定义一个接口,接口的名字一般以I开头
//格式: interface 接口的名称 {成员}
interface IPeople
{
string Name { get; set; }
double Height { get; set; }
void FF();
}
//当某个类或者结构体实现一个接口的时候,必须实现这个接口所有的成员
interface IPerson
{
string Sex { get; set; }
}
//一个类可以使用,实现多个接口
class All : IPeople, IPerson
{
public string Name { get; set; }
public double Height { get; set; }
public string Sex { get; set; }
public void FF() { }
}
interface IStudent
{
string Name { get; set; }
int Age { get; set; }
}
interface IAdult
{
double Height { get; set; }
}
class People : IStudent
{
public string Name { get; set; }
public double Height { get; set; }
public int Age { get; set; }
}
//: 作用 类的继承 接口的实现
class Student : People, IAdult
{
//当基类和接口中,拥有同名的属性的时候,派生类不需要自己实现
//可以用new关键字重新实现
public new double Height { get; set; }
}
}
//多接口
interface IA
{
string A { get; set; }
string B { get; set; }
int C { get; set; }
void FF(int f);
}
interface IB
{
string B { get; set; }
string C { get; set; }
string D { get; set; }
void FF(string f);
}
//一个类可以实现多个接口
class Both : IA, IB
{
public string A { get; set; }
//当一个类实现多个接口的时候,如果多个接口拥有相同类型的属性,只需要实现一个即可
public string B { get; set; }
public string D { get; set; }
//当一个类显示多个接口的时候,如果多个接口拥有不同类型的相同的属性,需要显示接口实现
//显示接口实现 不需要也不能加访问修饰符,这个成员访问需要将对象表示为对应的接口类型
int IA.C { get; set; }
string IB.C { get; set; }
//因为方法可以重载 ,所以可以直接重载两个接口的方法
public void FF(int f) { }
public void FF(string f) { }
}
interface IPeople
{
string Name { get; set; }
int Age { get; set; }
}
interface IStudent : IPeople
{
string StudentId { get; set; }
void Study();
}
//一个接口可以继承另外一个接口,如果一个接口b继承了接口a,某个类实现了接口b的时候,要实现a和b所有的成员
class Student : IStudent
{
//鼠标悬浮到报错的地方,--->显示可能修补的程序-->实现接口
public string StudentId { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public string Name { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public int Age { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public void Study()
{
throw new NotImplementedException();
}
}
总结:
接口在C#中提供了一种标准化的方式来定义类或结构应遵循的合同。它们提高了代码的可维护性和扩展性,使得不同的类可以实现相同的方法,从而方便统一管理和调用