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() 方法,展示了多态性。
相关推荐
R-G-B1 小时前
【33】C# WinForm入门到精通 ——表格布局器TableLayoutPanel【属性、方法、事件、实例、源码】
开发语言·c#·c# winform·表格布局器·tablelayoutpane
freesheep7202 小时前
WPF使用PreviewTextInput事件限制用户输入
c#·wpf
Yueeyuee_4 小时前
【C#学习Day16笔记】XML文件、 事件Event 、Json数据
笔记·学习·c#
钢铁男儿7 小时前
C# 枚举器和迭代器(常见迭代器模式)
数据库·c#·迭代器模式
R-G-B9 小时前
【05】VM二次开发——模块参数配置--带渲染/不带渲染(WinForm界面调用 模块参数配置)
c#·vm二次开发·vm模块参数配置·vm在winform界面调用
R-G-B16 小时前
【12】大恒相机SDK C#开发 ——多相机开发,枚举所有相机,并按配置文件中的相机顺序 将所有相机加入设备列表,以便于对每个指定的相机操作
c#·大恒相机sdk·大恒多相机开发·大恒多相机枚举·大恒多相机指定顺序
R-G-B16 小时前
【13】大恒相机SDK C#开发 —— Fom1中实时处理的8个图像 实时显示在Form2界面的 pictureBox中
c#·大恒相机sdk·图像实时显示在另一个界面
向宇it1 天前
【unity小技巧】封装一套 Unity 的植物生长系统
游戏·unity·c#·游戏引擎
NFA晨曦1 天前
力扣刷题日常(7-8)
算法·leetcode·c#
踏上青云路1 天前
C# 闭包
java·前端·c#