代码改变世界

C#进阶 Methods下 Extension Methods

2010-12-25 13:46  撞破南墙  阅读(1741)  评论(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()); 
        }
    } 
}

 

 

 值得注意的是 在Program 的.CS文件里 并没有 引用 扩展方法的命名空间,

因为他的命名空间就是SYSTEM...这个又好又坏,对于多人来说,按理说命名空间不要取默认的。.23

 

 

一些说明:

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

 

 

24

 

3更多细节

在你使用this参数扩展了方法之后,该程序集会在编译的时候会在对应静态类上加上类似以下的东西。以便于调用的时候方便找到。

 

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets. 
Assembly)] 
public sealed class ExtensionAttribute : Attribute { 
}

 

 

而他其实在运行时是需要引用System.Core.dll的。

 

4扩展阅读

扩展方法是我非常喜欢的一个特性,因为会让代码变漂亮很多。 代码的可读性是很重要的。

不能不说的C#特性-扩展方法

c#扩展方法奇思妙用