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();

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

扩展方法本质

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

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

相关推荐
zmzb01031 小时前
C++课后习题训练记录Day109
开发语言·c++
wjs20241 小时前
SQL AVG() 函数详解
开发语言
上单带刀不带妹2 小时前
【Axios 实战】网络图片地址转 File 对象,附跨域解决方案
开发语言·前端·javascript·vue
有一个好名字2 小时前
JAVA虚拟机-JVM
java·开发语言·jvm
一个处女座的程序猿O(∩_∩)O2 小时前
Python多重继承详解
开发语言·python
SmartBrain2 小时前
技术总结:VLLM部署Qwen3模型的详解
开发语言·人工智能·算法·vllm
wuqingshun3141592 小时前
HashMap的长度为什么是2的N次方呢?
java·开发语言·jvm
岱宗夫up2 小时前
【前端基础】HTML + CSS + JavaScript 基础(二)
开发语言·前端·javascript·css·架构·前端框架·html
xyq20242 小时前
C++ 类 & 对象
开发语言