c# 接口

  1. 在 C# 中,接口是一种定义了一组方法、属性、事件或索引器的契约,但不提供具体实现。任何类或结构体都可以实现一个或多个接口,从而承诺提供接口中定义的功能。
  2. 特点:定义方法:接口只定义方法的签名,没有实现。
    多重继承:一个类可以实现多个接口,允许不同类型的行为组合。
    多态性:可以通过接口类型引用不同实现,从而实现代码的灵活性和可扩展性。
  3. 实例1:
点击查看代码
public interface IFly
{
    void Fly();
}

public class Bird : IFly
{
    public void Fly() 
    {
        Console.WriteLine("Bird is flying.");
    }
}

点击查看代码
 
实例2program:
----------------------------
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)
        {
            // Plane p = new Plane();
            //p.Fly();
            //p.FlyAttack();
            // Brid b = new Brid();
            //b.Fly();
            //b.FlyAttack();

            IFly fly;//声明一个fly
            fly = new Plane();//把Plane赋给fly
            fly.Fly();//fly有了Plane的功能
            fly.FlyAttack();

            fly = new Brid();
            fly.FlyAttack();
            fly.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("小鸟在空中攻击");
        }
    }
}

posted @   神乐羊  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示
主题色彩