C# 扩展方法[学习]
C#中可以定义扩展方法,还可以为集合做扩展方法。
示例如下:

using System;
using System.Collections.Generic;
using MySpace; //注意:引入扩展方法的空间
namespace Con_1
{
class Program
{
static void Main(string[] args)
{
string str = "{0}先生。".With("XuGang");
Console.WriteLine("您好!" + str);
//2调用集合的扩展方法
str.ShowItems<char>();
}
}
}
namespace MySpace
{
//扩展方法必须在非泛型静态类中定义
public static class MyMethods
{
//注意:第一个参数使用“this”获得当前对象
public static string With(this string _context, params string[] _args)
{
return string.Format(_context,_args);
}
//2为集合做扩展方法
public static void ShowItems<T>(this IEnumerable<T> _al)
{
foreach (var item in _al)
{
Console.WriteLine(item);
}
}
}
}
using System.Collections.Generic;
using MySpace; //注意:引入扩展方法的空间
namespace Con_1
{
class Program
{
static void Main(string[] args)
{
string str = "{0}先生。".With("XuGang");
Console.WriteLine("您好!" + str);
//2调用集合的扩展方法
str.ShowItems<char>();
}
}
}
namespace MySpace
{
//扩展方法必须在非泛型静态类中定义
public static class MyMethods
{
//注意:第一个参数使用“this”获得当前对象
public static string With(this string _context, params string[] _args)
{
return string.Format(_context,_args);
}
//2为集合做扩展方法
public static void ShowItems<T>(this IEnumerable<T> _al)
{
foreach (var item in _al)
{
Console.WriteLine(item);
}
}
}
}
注意:
1 C# 只支持扩展方法,不支持扩展属性、扩展事件等;
2 方法名无限制,第一个参数必须带 this ;
3 扩展方法的命名空间可以使用 namespace System ,但不推荐;
4 定义扩展方法的类是静态类;
在使用this 参数扩展了方法之后,该程序集会在编译的时候会在对应静态类上加上类似以下的东西。以便于调用的时候方便找到。
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
public sealed class ExtensionAttribute : Attribute
{
......
}
public sealed class ExtensionAttribute : Attribute
{
......
}
MSIL 中,自动添加了如下的代码:
.custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 )
可以看出,在运行时是需要引用 System.Core.dll。
参考来源:
C#进阶 Methods下 Extension Methods
作者: XuGang 网名:钢钢 |
出处: http://xugang.cnblogs.com |
声明: 本文版权归作者和博客园共有。转载时必须保留此段声明,且在文章页面明显位置给出原文连接地址! |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?