C# 扩展方法[学习]
来源:互联网 发布:方维拼团源码下载 编辑:程序博客网 时间:2024/05/21 11:36
C# 扩展方法[学习]
C#中可以定义扩展方法,还可以为集合做扩展方法。
示例如下:
扩展方法
using System;
using System.Collections.Generic;
using MySpace;//注意:引入扩展方法的空间
namespace Con_1
{
class Program
{
staticvoid Main(string[] args)
{
string str= "{0}先生。".With("XuGang");
Console.WriteLine("您好!"+ str);
//2调用集合的扩展方法
str.ShowItems<char>();
}
}
}
namespace MySpace
{
//扩展方法必须在非泛型静态类中定义
publicstatic class MyMethods
{
//注意:第一个参数使用“this”获得当前对象
publicstatic string With(thisstring _context,params string[] _args)
{
returnstring.Format(_context,_args);
}
//2为集合做扩展方法
publicstatic void ShowItems<T>(this IEnumerable<T> _al)
{
foreach (var itemin _al)
{
Console.WriteLine(item);
}
}
}
}
using System.Collections.Generic;
using MySpace;//注意:引入扩展方法的空间
namespace Con_1
{
class Program
{
staticvoid Main(string[] args)
{
string str= "{0}先生。".With("XuGang");
Console.WriteLine("您好!"+ str);
//2调用集合的扩展方法
str.ShowItems<char>();
}
}
}
namespace MySpace
{
//扩展方法必须在非泛型静态类中定义
publicstatic class MyMethods
{
//注意:第一个参数使用“this”获得当前对象
publicstatic string With(thisstring _context,params string[] _args)
{
returnstring.Format(_context,_args);
}
//2为集合做扩展方法
publicstatic void ShowItems<T>(this IEnumerable<T> _al)
{
foreach (var itemin _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 0000 00 )
可以看出,在运行时是需要引用 System.Core.dll。
- C# 扩展方法[学习]
- c#学习-扩展方法
- c#学习笔记之扩展方法
- C#中的扩展方法学习总结
- C#中的扩展方法学习总结
- c#中的扩展方法
- C# 扩展方法
- C#扩展方法本质
- C#扩展方法
- 关于C#扩展方法
- C#之扩展方法
- C#2008扩展方法
- C# 扩展方法
- C#扩展方法
- C#扩展方法
- C#扩展方法
- C# 扩展方法
- C# 扩展方法简介
- 官方给的 JXLS 读取 excel 文件的例子
- C#多线程学习(六) 互斥对象
- 框架转换与存储过程拼接_0830
- 收藏.NET 技术社区
- AspxGridView控件的常用操作
- C# 扩展方法[学习]
- V5shop 8.2版本下通杀注入漏洞
- 配置魔药(medic.pas/c/cpp)
- Qt Plugin简单示例
- WinForm 窗体间传递数据的一些方法[转]
- MO_GLOBAL - EBS R12 中 Multi Org 设计的深入研究
- I Believe I Can Fly
- android之Itent.ACTION_PICK Intent.ACTION_GET_CONTENT妙用
- 理解值与引用[学习]