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 类,并实现了 iNBAPlayable 和 iSupermanable 接口。
    • teacher 类实现了 iNBAPlayable 和 iSupermanable 接口。
  3. 多态性 :
    • 在 Main 方法中,iNBAPlayable 接口类型的变量 nBA 和 nBA1 分别被赋值为 Student 和 teacher 类的实例。通过接口调用 KouLan() 方法,展示了多态性。
相关推荐
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
神仙别闹3 天前
基于C#+MySQL实现(WinForm)个人聊天室软件
c#
kybs19913 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
Polevne3 天前
C# SFTP客户端实现文件传输
c#·ssh
samble3 天前
从零搭建灌装监控系统(四):深色主题与样式系统,ResourceDictionary 统一管理
c#·wpf·mvvm·样式·工业控制
cjp5603 天前
024 . WPF MVVM类封装优化
c#
淡海水3 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
asdzx673 天前
如何使用 C# 提取 PPT 文本与图片
c#·ppt·提取文本
2501_930707784 天前
使用C#代码使用条件格式为 Excel 隔行设置颜色
c#·excel
何以解忧唯有撸码4 天前
【开源】c#造个轮子-日程安排工具
c#·自定义控件