C#进阶 Methods下 Extension Methods
2010-12-25 13:46 撞破南墙 阅读(1752) 评论(0) 编辑 收藏 举报1 c#的扩展方法
从一个简单的例子开始
namespace System {
public static class Class4 {
public static string With(this string content, params string[] strs) {
return string.Format(content, strs);
}
}
}
.................主程序..............
using System;
namespace CLRLearn {
class Program {
static void Main(string[] args) {
Display("hi {0}and{1} !".With(" ladys ", " gentleman !"));
Console.Read();
}
static void Display(object ob) {
Console.WriteLine(DateTime.Now.ToString() + " " + ob.ToString());
}
}
}
public static class Class4 {
public static string With(this string content, params string[] strs) {
return string.Format(content, strs);
}
}
}
.................主程序..............
using System;
namespace CLRLearn {
class Program {
static void Main(string[] args) {
Display("hi {0}and{1} !".With(" ladys ", " gentleman !"));
Console.Read();
}
static void Display(object ob) {
Console.WriteLine(DateTime.Now.ToString() + " " + ob.ToString());
}
}
}
值得注意的是 在Program 的.CS文件里 并没有 引用 扩展方法的命名空间,
因为他的命名空间就是SYSTEM...这个又好又坏,对于多人来说,按理说命名空间不要取默认的。.
一些说明:
1 C#只支持扩展方法,不支持扩展属性,扩展事件。。。等
2 方法名无限制,第一个参数必须带this
2为集合做扩展方法
public static void ShowItems<T>(this IEnumerable<T> collection) {
foreach (var item in collection)
Console.WriteLine(item);
}
static void Main(string[] args) {
string statment= "hi {0} and {1}".With("ladys", "gentleman");
Display(statment);
statment.ShowItems<char>();
Console.Read();
}
foreach (var item in collection)
Console.WriteLine(item);
}
static void Main(string[] args) {
string statment= "hi {0} and {1}".With("ladys", "gentleman");
Display(statment);
statment.ShowItems<char>();
Console.Read();
}
3更多细节
在你使用this参数扩展了方法之后,该程序集会在编译的时候会在对应静态类上加上类似以下的东西。以便于调用的时候方便找到。
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.
Assembly)]
public sealed class ExtensionAttribute : Attribute {
}
Assembly)]
public sealed class ExtensionAttribute : Attribute {
}
而他其实在运行时是需要引用System.Core.dll的。
1 |
4扩展阅读
扩展方法是我非常喜欢的一个特性,因为会让代码变漂亮很多。 代码的可读性是很重要的。
c#扩展方法奇思妙用
作者:撞破南墙
出处:http://www.cnblogs.com/facingwaller/
关于作者:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述