C# 擴充方法(Extension Method)

來源:互聯網
上載者:User

有時有這樣的情況,有一個密封類,你不能修改它,但你又想對它擴充(添加一個方法),這個時候就可以用到擴充方法了。請看下面的例子:

 

class Program{    static void Main(string[] args)    {        SealedClass x = new SealedClass();        Console.WriteLine(x.TestMethod());    }}sealed class SealedClass{}static class SealedClassExtension{    public static string TestMethod(this SealedClass x)    {        return "";    }}

雖然SealedClass是一個密封類,但我們依然似乎為它添加了一個TestMethod的方法。以TestMethod為例,擴充方法有下面兩個特徵:

(1)是靜態方法

(2)參數中使用了this關鍵字

 

上面講到如何擴充一個類,下面再看一個擴充介面的例子。

 

public static class Enumerable{    public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func);            }

我們經常使用到執行了IEnumerable<T>的容器,比如說List<T>。這些容器因為執行了IEnumerable<T>介面,所以都能使用一些方法,比如Aggregate。如果去看IEnumerable<T>介面的定義,並沒有包含Aggregate方法,所以Aggregate實際是一個擴充方法。它是在靜態類Enumerable中定義的。

 

所以Aggregate就是對IEnumerable<T>介面的擴充方法。

總結:

(1)注意擴充方法的文法。

(2)可以對類進行擴充,也可以對介面進行擴充。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.