接口定义了将由类或结构实现的契约。它可以包含方法、属性、事件和索引器。接口与类类似,只不过它不保存任何数据,仅指定它可以执行的行为(或更准确地说,实现它的类可以执行的行为)。
类可以实现一个行为或更多接口。要实现接口成员,类应具有与接口成员具有相同方法定义的公共成员,即相同的名称和签名。
例如,icomparer 是在 system.collections 命名空间中定义的接口它定义了比较两个对象的方法的契约。 car类实现了icomparer接口
public interface idriver{ void drive();}public class car : idriver{ public string name { get; set; } public int speed { get; set; } public void drive(){ console.writeline($"{name}: {speed}"); }}
接口上的所有成员都是隐式抽象的,并且没有任何实现细节。所有接口成员都是公共的。不能将访问修饰符与接口成员一起使用。实现接口的类必须提供实现该接口的公共方法。
接口可以扩展其他接口,例如 -
public interface iperformer { void perform(); }public interface isinger : iperformer{ void sing();}
接口允许您将来自多个源的行为包含在一个类中。由于 c# 不像 c++ 那样允许多重继承,因此接口是在 c# 中实现多重继承的一种方法。
接口的一个缺点是,当您使用接口公开 api 时,接口的灵活性不如类。当您更改接口的约定时,实现该接口的所有类都会中断,并且需要更新才能实现该接口。
示例 实时演示
using system;class program{ static void main(){ var carone = new car { name = "honda", speed = 100 }; var cartwo = new car { name = "toyota", speed = 70 }; carone.drive(); cartwo.drive(); }}public interface idriver{ void drive();}public class car : idriver{ public string name { get; set; } public int speed { get; set; } public void drive(){ console.writeline($"{name}: {speed}"); }}
输出honda: 100toyota: 70
以上就是c# 中的接口如何工作?的详细内容。