Net C# 扩展方法
Net C# 擴展方法
擴展方法使您能夠向現有類型“添加”方法,而無需創建新的派生類型、重新編譯或以其他方式修改原始類型。擴展方法是一種特殊的靜態方法,但可以像擴展類型上的實例方法一樣進行調用。
好處:
不修改原有類型的實現
調用:
調用以成員函數方式調用,靜態實現
范例:
using System.Linq;
using System.Text;
using System;
namespace CustomExtensions
{
??? //Extension methods must be defined in a static class
??? public static class StringExtension
??? {
??????? // This is the extension method.
??????? // The first parameter takes the "this" modifier
??????? // and specifies the type for which the method is defined.
??????? public static int WordCount(this String str)
??????? {
??????????? return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
??????? }
??? }
}
namespace Extension_Methods_Simple
{
??? //Import the extension method namespace.
??? using CustomExtensions;
??? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? string s = "The quick brown fox jumped over the lazy dog.";
??????????? //? Call the method as if it were an
??????????? //? instance method on the type. Note that the first
??????????? //? parameter is not specified by the calling code.
??????????? int i = s.WordCount();
??????????? System.Console.WriteLine("Word count of s is {0}", i);
??????? }
??? }
}
上述代碼實現的字統計
你也可以采用繼承的方式來實現
public class StringExtension : String
{
??? public int WordCount()
??? {
??? ......
??? }
}
調用上,這是兩個不同的類別處理。
=======================================================
看到這里,如果學習Objective-C,就知道Category這個東西,就是用于擴展方法。
看來C#這個語言,從多類語言中吸取各自的優點,混裝了自己~
至于Objective-C的Category,這里不做介紹和比對
=======================================================
轉載于:https://www.cnblogs.com/GoGoagg/archive/2011/08/04/2127697.html
總結
以上是生活随笔為你收集整理的Net C# 扩展方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ubuntu下Memcache的安装与基
- 下一篇: StreamWriter类的一般使用方法