日期:2010-09-14  浏览次数:20394 次

扩展方法(Extension Method)
可以为已有的类型添加新的方法定义和实现,比如int类型目前没有一个名叫xxxyyy()的方法,
那么通过使用扩展方法,我们可以为int类型添加一个xxxyyy()方法。
这个有点类似于用来扩展系统功能的某些设计模式。

下面我们用代码来说话:
这是我们以前的写法:

   1public static class Extensions
 2{
 3    public static string CamelCase(string identifier)
 4{
 5            string newString = "";
 6            bool sawUnderscore = false;
 7
 8            foreach (char c in identifier)
 9            {
10                if ((newString.Length == 0) && Char.IsLetter(c))
11                    newString += Char.ToUpper(c);
12                else if (c == '_')
13                    sawUnderscore = true;
14                else if (sawUnderscore)
15                {
16                        newString += Char.ToUpper(c);
17                        sawUnderscore = false;
18                }
19                else
20                        newString += c;
21        }
22
23            return newString;
24}           
25}
26
27static void Main(string[] args)
28{
29string[] identifiers = new string[] {
30         "do_something",
31         "find_all_objects",
32          "get_last_dict_entry"
33         };
34
35foreach (string s in identifiers)
36     Console.WriteLine("{0} becomes: {1}", s, Extensions.CamelCase(s));
37}
38
C# 3.0中我们可以这样写:
 1public static class Extensions
 2{
 3    public static string CamelCase(this string identifier)
 4{
 5            string newString = "";
 6            bool sawUnderscore = false;
 7
 8            foreach (char c in identifier)
 9            {
10                if ((newString.Length == 0) && Char.IsLetter(c))
11                    newString += Char.ToUpper(c);
12                els