C# 3.0新特性初步研究 Part2:使用扩展方法
2006-06-10 19:29
991 查看
扩展方法(Extension Method)
可以为已有的类型添加新的方法定义和实现,比如int类型目前没有一个名叫xxxyyy()的方法,
那么通过使用扩展方法,我们可以为int类型添加一个xxxyyy()方法。
这个有点类似于用来扩展系统功能的某些设计模式。
下面我们用代码来说话:
这是我们以前的写法:
1public static class Extensions
2
27static void Main(string[] args)
28
C# 3.0中我们可以这样写:
1public static class Extensions
2
27static void Main(string[] args)
28public static string CamelCase(this string identifier)
2Console.WriteLine("{0} becomes: {1}", s, s.CamelCase());
变量s原本是一个string类型,并没有CamelCase()方法,但是我们在CamelCase()方法的参数列表最前面加上一个this关键字,
则string s就拥有了一个新的方法CamelCase,很简单也很直接 :)
下面我们看一看一个稍微复杂一点的应用:
1public static class Extensions
2
11static void Main(string[] args)
12var odds = new List<int>();
14odds.Add(1);
15odds.Add(3);
16odds.Add(5);
17odds.Add(7);
18
19var evens = new List<int>();
20evens.Add(0);
21evens.Add(2);
22evens.Add(4);
23evens.Add(6);
24
25var both = odds.Combine(evens);
26Console.WriteLine("Contents of 'both' list:");
27foreach (int i in both)
28 Console.WriteLine(i);
29}
怎%
可以为已有的类型添加新的方法定义和实现,比如int类型目前没有一个名叫xxxyyy()的方法,
那么通过使用扩展方法,我们可以为int类型添加一个xxxyyy()方法。
这个有点类似于用来扩展系统功能的某些设计模式。
下面我们用代码来说话:
这是我们以前的写法:
1public static class Extensions
2
27static void Main(string[] args)
28
C# 3.0中我们可以这样写:
1public static class Extensions
2
27static void Main(string[] args)
28public static string CamelCase(this string identifier)
2Console.WriteLine("{0} becomes: {1}", s, s.CamelCase());
变量s原本是一个string类型,并没有CamelCase()方法,但是我们在CamelCase()方法的参数列表最前面加上一个this关键字,
则string s就拥有了一个新的方法CamelCase,很简单也很直接 :)
下面我们看一看一个稍微复杂一点的应用:
1public static class Extensions
2
11static void Main(string[] args)
12var odds = new List<int>();
14odds.Add(1);
15odds.Add(3);
16odds.Add(5);
17odds.Add(7);
18
19var evens = new List<int>();
20evens.Add(0);
21evens.Add(2);
22evens.Add(4);
23evens.Add(6);
24
25var both = odds.Combine(evens);
26Console.WriteLine("Contents of 'both' list:");
27foreach (int i in both)
28 Console.WriteLine(i);
29}
怎%
相关文章推荐
- C# 3.0新特性初步研究 Part2:使用扩展方法_C#教程
- C# 3.0新特性初步研究 Part2:使用扩展方法_C#教程
- C# 3.0新特性初步研究 Part2:使用扩展方法_C#教程
- C# 3.0新特性初步研究 Part1:使用隐含类型的本地变量
- C# 3.0新特性初步研究 Part6:使用查询表达式 _C#教程
- C# 3.0新特性初步研究 Part1:使用隐含类型的本地变量
- C# 3.0新特性初步研究 Part3:使用拉姆达表达式
- C# 3.0新特性初步研究 Part6:使用查询表达式 _C#教程
- C# 3.0新特性初步研究 Part3:使用拉姆达表达式_C#教程
- C# 3.0新特性初步研究 Part6:使用查询表达式 _C#教程
- C# 3.0新特性初步研究 Part4:使用集合类型初始化器_C#教程
- C# 3.0新特性初步研究 Part1:使用隐含类型的本地变量_C#教程
- C# 3.0新特性初步研究 Part4:使用集合类型初始化器
- C# 3.0新特性初步研究 Part4:使用集合类型初始化器_C#教程
- C# 3.0新特性初步研究 Part3:使用拉姆达表达式_C#教程
- c# 3.0新特性之使用扩展方法
- C# 3.0新特性初步研究 Part3:使用拉姆达表达式_C#教程
- C# 3.0新特性初步研究 Part6:使用查询表达式
- C# 3.0新特性初步研究 Part1:使用隐含类型的本地变量_C#教程
- C# 3.0新特性初步研究 Part1:使用隐含类型的本地变量_C#教程