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() 方法,展示了多态性。
相关推荐
iCxhust1 小时前
c# U盘映像生成工具
开发语言·单片机·c#
emplace_back3 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
阿蒙Amon4 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#
深海潜水员5 小时前
【Behavior Tree】-- 行为树AI逻辑实现- Unity 游戏引擎实现
游戏·unity·c#
开开心心_Every5 小时前
便捷的Office批量转PDF工具
开发语言·人工智能·r语言·pdf·c#·音视频·symfony
小码编匠7 小时前
C# 上位机开发怎么学?给自动化工程师的建议
后端·c#·.net
钢铁男儿7 小时前
C# 接口(什么是接口)
java·数据库·c#
小老鼠爱大米11 小时前
C# WPF - Prism 学习篇:搭建项目(一)
c#·wpf·prism