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# 擴充方法奇思妙用