C# & Unity 面向对象补全计划 之 接口

本文仅作学习笔记与交流,不作任何商业用途,作者能力有限,如有不足还请斧正

本系列旨在通过补全学习之后,给出任意类图都能实现并做到逻辑上严丝合缝

1.接口

在 C# 中,接口(interface)是一种定义了一组方法、属性和事件的类型

接口只包含成员的声明,而不包含任何实现实现接口 的类必须提供 这些成员的具体实现

接口的主要作用是定义类或结构必须遵循的合同,从而确保一致性和可替换性

接口的规范与特点

2.使用

一个类可以实现多个接口,当一个类实现多个接口时,如果这些接口中有相同签名的成员(方法、属性、事件等),你只需要在类中实现一次即可,这是因为接口成员的实现是基于成员的签名,而不是接口本身

声明:

cs 复制代码
public interface MyIntface
    {
    //属性
    int PropertyName {
        get; set;
    }
    //方法
    void MethodName();
    //事件
    event EventHandler EventName;
    //索引器
    string this[int index] { get; set; }
}

public interface MyIntface2 {
    //属性
    int PropertyName {
        get; set;
    }
    //方法
    void MethodName();
    //事件
    event EventHandler EventName;
    //索引器
    string this[int index] { get; set; }
}

实现:visual studio将鼠标放到继承的接口关键字上,alt+enter自动实现接口

cs 复制代码
public class I : MyIntface,MyIntface2{

    public string this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

    public int PropertyName {
        get => throw new NotImplementedException();
        set => throw new NotImplementedException();
    }

    public event EventHandler EventName;

    public void MethodName() {
        throw new NotImplementedException();
    }
}

如果你想分别实现不同接口中的同名成员时,可以使用显式实现的方式:

cs 复制代码
public int PropertyName {
    get => throw new NotImplementedException();
    set => throw new NotImplementedException();
}

 int MyIntface2.PropertyName {
    get => throw new NotImplementedException();
    set => throw new NotImplementedException();
}

3.比较

主要是与抽象类比较,因为二者的相似点是抽象类的抽象方法在声明时也不需要实现

但是也二者相似也仅此而已了

相关推荐
小码编匠18 小时前
WPF 中的高级交互通过右键拖动实现图像灵活缩放
后端·c#·.net
SmalBox19 小时前
【光照】[漫反射diffuse]以UnityURP为例
unity·渲染
使一颗心免于哀伤1 天前
《设计模式之禅》笔记摘录 - 21.状态模式
笔记·设计模式
唐青枫1 天前
C#.NET 定时任务与队列利器:Hangfire 完整教程
c#·.net
hez20101 天前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
SmalBox2 天前
【光照】[自发光Emission]以UnityURP为例
unity·渲染
mudtools2 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools3 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
SmalBox3 天前
【光照】Unity中的[经验模型]
unity·渲染