- 在 C# 中,接口是一种定义了一组方法、属性、事件或索引器的契约,但不提供具体实现。任何类或结构体都可以实现一个或多个接口,从而承诺提供接口中定义的功能。
- 特点:定义方法:接口只定义方法的签名,没有实现。
多重继承:一个类可以实现多个接口,允许不同类型的行为组合。
多态性:可以通过接口类型引用不同实现,从而实现代码的灵活性和可扩展性。
- 实例1:
点击查看代码
public interface IFly
{
void Fly();
}
public class Bird : IFly
{
public void Fly()
{
Console.WriteLine("Bird is flying.");
}
}
点击查看代码
实例2:
program:
----------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_09_接口
{
internal class Program
{
static void Main(string[] args)
{
IFly fly;
fly = new Plane();
fly.Fly();
fly.FlyAttack();
fly = new Brid();
fly.FlyAttack();
fly.Fly();
}
}
}
----------------------
IFly
----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_09_接口
{
interface IFly
{
void Fly();
void FlyAttack();
}
}
----------------------
Plane
----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_09_接口
{
class Plane : IFly
{
public void Fly()
{
Console.WriteLine("飞机在空中飞");
}
public void FlyAttack()
{
Console.WriteLine("飞机在空中攻击");
}
}
}
----------------------
bird
----------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test_09_接口
{
internal class Brid : IFly
{
public void Fly()
{
Console.WriteLine("小鸟在空中飞");
}
public void FlyAttack()
{
Console.WriteLine("小鸟在空中攻击");
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?