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() 方法,展示了多态性。
相关推荐
huaqianzkh2 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#
用户3721574261352 天前
C# 实现 Excel 单元格保护:锁定公式并允许编辑指定区域
c#·ai编程·编程语言
公子小六3 天前
基于.NET的Windows窗体编程之WinForms数据持久化(1)
windows·microsoft·c#·.net·winforms
三雷科技3 天前
第6章第4节:自定义分词器
开发语言·c#
zhanghaha13143 天前
C# 系列教程_12 字符串 string 保姆级系统教程(面向新手,大量示例 + 原理讲解)
开发语言·数据库·c#
Coder_Shenshen3 天前
罗克韦尔ACD工程归档离线变量树解析
算法·c#
寂寞的船4 天前
【Unity知识速递】第10期 Unity GC 零分配实战:从 UnityEngine.Pool 到手动 GC 控制的全链路优化
jvm·unity·c#·游戏引擎·lucene
1-1=04 天前
C# 数据结构和特殊类型
数据结构·c#·.net·.netcore
波力海苔夹心脆6756 天前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典
AI导出鸭PC端6 天前
Perplexity批量导出没有PDF模式?AI导出鸭插件补上最后一块拼图
人工智能·pdf·c#·ai导出鸭