C# 擴充方法[學習]

來源:互聯網
上載者:User

 

C#中可以定義 擴充方法,還可以 為集合做擴充方法

樣本如下:

擴充方法

using System;
using System.Collections.Generic; 

using MySpace; //注意:引入擴充方法的空間

namespace Con_1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "{0}先生。".With("XuGang");
            Console.WriteLine("您好!" + str);

            //2調用集合的擴充方法
            str.ShowItems<char>();
        }
    }
}

namespace MySpace
{
    //擴充方法必須在非泛型靜態類中定義
    public static class MyMethods
    {
        //注意:第一個參數使用“this”獲得當前對象
        public static string With(this string _context, params string[] _args)
        {
            return string.Format(_context,_args);
        }

        //2為集合做擴充方法
        public static void ShowItems<T>(this IEnumerable<T> _al)
        {
            foreach (var item in _al)
            {
                Console.WriteLine(item);
            }
        }
    }
}

注意:

1  C# 只支援擴充方法,不支援擴充屬性、擴充事件等;

2  方法名無限制,第一個參數必須帶 this ;

3  擴充方法的命名空間可以使用 namespace System ,但不推薦;

4  定義擴充方法的類是靜態類;

 

在使用this 參數擴充了方法之後,該程式集會在編譯的時候會在對應靜態類上加上類似以下的東西。以便於調用的時候方便找到。[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)] 
public sealed class ExtensionAttribute : Attribute 

  ......
}

MSIL 中,自動添加了如下的代碼:.custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) 可以看出,在運行時是需要引用 System.Core.dll。

 

參考來源:

C#進階 Methods下 Extension Methods

不能不說的C# 特性-擴充方法

C# 擴充方法奇思妙用

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.