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

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

扩展方法本质

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

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

相关推荐
qq_2258917466几秒前
基于Flask的空气质量监测与预测分析系统
开发语言·后端·python·信息可视化·django·flask
lhldsg14 分钟前
社区健身系统开发实战:从需求分析到落地部署全流程指南
java·开发语言·小程序·需求分析
李高钢15 分钟前
C# WPF Prism 进阶(三):导航(Navigation)深入
开发语言·c#·wpf
冯汉栩16 分钟前
Swift Control DashLineView(虚线)
开发语言·ios·swift
覆东流23 分钟前
4.Java运算符与表达式
java·开发语言·后端
SomeB1oody1 小时前
【RustyML入门】5.1. 回归指标
开发语言·后端·机器学习·rust·教程
龙虾PRO1 小时前
2026 DeepSeek Harness 部署完整教程:npx 一键启动至 Python SDK 全流程接入
开发语言·python
我是苏苏1 小时前
C#基础:不写for循环的五种方式
数据结构·算法·c#
小新讲网安3 小时前
WiFi安全攻防实战:WPA3新协议与传统破解技术全解析
开发语言·网络·安全·php·漏洞·nmap·漏洞检测
必须会一定会9 小时前
Agent Plugins 1.0实战:plugin.json、skills、mcp.json目录结构与迁移
开发语言·人工智能·ai编程