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() 方法,展示了多态性。
相关推荐
用户8356290780512 小时前
C# 自动化生成 PowerPoint 演示文稿
后端·c#
饮品爱好者3 小时前
[C#] NO.4 我的第一个项目
vscode·职场和发展·c#·github
专注VB编程开发20年5 小时前
.net按地址动态调用VC++DLL将非托管DLL中的函数地址转换为.NET可调用的委托
开发语言·c++·c#·.net
玩泥巴的6 小时前
.NET驾驭Excel之力:工作簿与工作表操作基础
c#·excel·二次开发·office·com互操作
czhc11400756637 小时前
C# 1116 流程控制 常量
开发语言·c#
葛小白17 小时前
C#进阶12:C#全局路径规划算法_Dijkstra
算法·c#·dijkstra算法
yivifu8 小时前
精益求精,支持处理嵌套表格的Word表格转HTML表格
开发语言·c#·word
唐青枫9 小时前
C#.NET 全局异常到底怎么做?最完整的实战指南
c#·.net
Charles_go1 天前
C#13、什么是部分类
开发语言·c#
ghie90901 天前
C#语言中使用“using“关键字的介绍
开发语言·c#