C#接口代码记录

cs 复制代码
using System;

namespace InterfacesExample
{
    // 定义接口
    public interface INBAPlayable
    {
        void KouLan();
    }

    public interface ISupermanable
    {
        void Fly();
    }

    // 基类
    public class Person
    {
        public void CHLSS()
        {
            Console.WriteLine("人类吃喝拉撒睡");
        }
    }

    // Student 类实现多个接口
    public class Student : Person, INBAPlayable, ISupermanable
    {
        public void KouLan()
        {
            Console.WriteLine("学生可以扣篮");
        }

        public void Fly()
        {
            Console.WriteLine("学生会飞");
        }

        public void Study()
        {
            // 示例方法
        }
    }

    // teacher 类实现多个接口
    public class Teacher : INBAPlayable, ISupermanable
    {
        public void Fly()
        {
            Console.WriteLine("教师会飞");
        }

        public void KouLan()
        {
            Console.WriteLine("教师会扣篮");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            INBAPlayable nBA = new Student();
            nBA.KouLan();

            INBAPlayable nBA1 = new Teacher();
            nBA1.KouLan();

            Person p = new Student();
            p.CHLSS();

            Console.ReadKey();
        }
    }
}

代码分析

  1. 接口定义
    • iNBAPlayable 接口定义了一个方法 KouLan()
    • iSupermanable 接口定义了一个方法 Fly()
  2. 类实现
    • Student 类继承自 Person 类,并实现了 iNBAPlayableiSupermanable 接口。
    • teacher 类实现了 iNBAPlayableiSupermanable 接口。
  3. 多态性
    • Main 方法中,iNBAPlayable 接口类型的变量 nBAnBA1 分别被赋值为 Studentteacher 类的实例。通过接口调用 KouLan() 方法,展示了多态性。
相关推荐
qq_454245031 小时前
BasicMethod.Map 设计框架:8 个并行基础模块的数学根基与实现
数据结构·算法·c#
Byron Loong2 小时前
【c#】Bitmap释放之 大象与蚊子
开发语言·c#
临风细雨3 小时前
从 Bun 的 Rust 重写,看 C# 如何重建 AI 基础设施层
人工智能·rust·c#
吴可可1233 小时前
C# CAD二次开发自定义实体实现
c#
z落落5 小时前
C# WinForm 线程池与事件等待+进度条暂停恢复实战案例
开发语言·c#
酷酷的身影7 小时前
Managers/APConfigManager.cs
开发语言·ui·c#
贾斯汀frank19 小时前
C# 15 类型系统改进:Union Types
开发语言·windows·c#
曹牧20 小时前
Visual Studio:输出路径
windows·c#
时代的狂20 小时前
如何理解 C# 的 async 和 await
c#·.netcore·async·await
xiaoshuaishuai81 天前
C# AI实现PR处理、单元测试
开发语言·c#·log4j