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() 方法,展示了多态性。
相关推荐
用户21991679703911 小时前
C# 14 中的新增功能
c#
垂葛酒肝汤2 小时前
放置挂机游戏的离线和在线收益unity实现
游戏·unity·c#
爱说实话4 小时前
C# 20260112
开发语言·c#
无风听海4 小时前
C#中实现类的值相等时需要保留null==null为true的语义
开发语言·c#
云草桑4 小时前
海外运单核心泡货计费术语:不计泡、计全泡、比例分泡
c#·asp.net·net·计泡·海运
精神小伙就是猛5 小时前
C# Task/ThreadPool async/await对比Golang GMP
开发语言·golang·c#
工程师0075 小时前
C#状态机
开发语言·c#·状态模式·状态机
开开心心_Every5 小时前
离线黑白照片上色工具:操作简单效果逼真
java·服务器·前端·学习·edge·c#·powerpoint