c#扩展方法

扩展方法基本概念

为现有非静态的变量类型 添加新方法

作用

提升程序扩展性

不需要在对象中重新写方法

不需要继承来添加方法

为别人封装的类型写额外的方法

特点

写在静态类中

一定是个静态函数

第一个参数为扩展目标

第一个参数用this修饰

语法

访问修饰符 static 返回值 函数名(this 扩展类名 参数名 参数类型 参数名 参数类型)

cs 复制代码
static class Tools{    
    public static void SpeakValue(this int value)
    {
     Console.WriteLine("为int扩展的方法"+value);
    }
    public static void SpeakStringInfo(this string str,string str2,string str3)
    {
        Console.WriteLine("为string扩展的方法");
        Console.WriteLine("调用");
        Console.WriteLine("传的参数"+str2 + str3);
    }
    public static void Fun2(this Test t)
    {
        Console.WriteLine("为Test的扩展方法");
    }
}

public static void SpeakValue(this int value)

是为int扩展了一个成员方法

成员方法是需要实例化对象后才能使用的

value代表 使用该方法的实例化对象

使用逻辑

在任意一个静态类中写方法为系统自带的或者自己写的类型(非静态的变量类型)增加新方法

为自定义的类型扩展方法

cs 复制代码
class Test
{
    public int i = 10;
    public void Fun1()
    {
        Console.WriteLine("123");

    }
    public void Fun2()
    {
        Console.WriteLine("44");

    }  
}

扩展方法的使用

cs 复制代码
int i = 10;
i.SpeakValue();

string str = "000";
str.SpeakStringInfo("11", "22");
Test t = new Test();
t.Fun2();

如果扩展方法和原方法重合,那么调用的是原方法

扩展方法本质

扩展方法在编译后会被编译成普通的静态方法调用。

因此,扩展方法并不会真正改变类型本身,它只是一种语法糖,让代码更简洁、更具可读性。

相关推荐
kkeeper~9 小时前
0基础C语言积跬步之字符函数与字符串函数(上)
c语言·开发语言
hhb_61810 小时前
Swift核心技术难点与实战案例解析
开发语言·ios·swift
一楼的猫10 小时前
从工具链视角对比:番茄作家助手 vs 第三方写作辅助方案
java·服务器·开发语言·前端·学习·chatgpt·ai写作
程序leo源10 小时前
Qt窗口详解
开发语言·数据库·c++·qt·青少年编程·c#
likerhood11 小时前
Java static 关键字从浅入深
java·开发语言
猫猫的小茶馆11 小时前
【Python】函数与模块化编程
linux·开发语言·arm开发·驱动开发·python·stm32
计算机安禾11 小时前
【c++面向对象编程】第38篇:设计原则(二):里氏替换、接口隔离与依赖倒置
开发语言·c++
_院长大人_11 小时前
Java Excel导出:如何实现自定义表头与字段顺序的完全控制
java·开发语言·后端·excel
code_whiter11 小时前
C++1进阶(继承)
开发语言·c++
来恩100311 小时前
JSTL的标签库种类
java·开发语言