http://huan-lin.blogspot.com/2009/01/csharp-3-extension-methods.html
摘要:本文將簡單介紹 C# 3.0 的新語法:擴充方法(extension methods)。
1: public static class StringExtension
2: {
3: // 字串反轉
4: public static string Reverse(string s)
5: {
6: if (String.IsNullOrEmpty(s))
7: return "";
8: char[] charArray = new char[s.Length];
9: int len = s.Length - 1;
10: for (int i = 0; i <= len; i++)
11: {
12: charArray[i] = s[len - i];
13: }
14: return new string(charArray);
15: }
16: }
1: class Program
2: {
3: static void Main(string[] args)
4: {
5: string s = "123456789";
6: Console.WriteLine(StringExtension.Reverse(s));
7: }
8: }
6: Console.WriteLine(s.Reverse());
4: public static string Reverse(this string s)
1: public static class DateTimeExt
2: {
3: // 將 DateTime 物件格式化成中華民國年份的日期字串.
4: public static string ToRocDateString(DateTime date, char separator)
5: {
6: int year = (date.Year - 1911);
7: return year.ToString() + separator + date.Month + separator + date.Day;
8: }
9: }
4: public static string ToRocDateString(this DateTime date, char separator)
Console.WriteLine(DateTime.Now.ToRocDate('/'));
你不用擔心呼叫擴充方法時會忘記要傳入哪些參數,Visual Studuo 的 IntelliSense 功能會提示你。