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() 方法,展示了多态性。
相关推荐
wkj0011 小时前
接口实现类向上转型和向上转型解析
java·开发语言·c#
阿伍.3 小时前
【指针】(适合考研、专升本)
c++·考研·c#
香煎三文鱼4 小时前
C# net8生成excel,并设置列规则导出文件
c#·excel·c#生成ecel
汪小白JIY5 小时前
【C#】多级缓存与多核CPU
缓存·c#·多级缓存
工程师0075 小时前
C#AES加密
网络·安全·web安全·c#
程序设计实验室7 小时前
提升Avalonia UI质感,跨平台图标库选型实践
c#·avalonia
我是苏苏11 小时前
C#高级:利用反射让字符串决定调用哪个方法
后端·c#
月巴月巴白勺合鸟月半16 小时前
工作记录 2017-08-01
c#·健康医疗
Rose 使者20 小时前
全网手机二次放号查询接口如何用C#进行调用?
c#·api·手机二次放号