C# 擴展方法[學習]
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);
}
}
}
}
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
{
......
}
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
| 作者: XuGang 網名:鋼鋼 |
| 出處: http://xugang.cnblogs.com |
| 聲明: 本文版權歸作者和博客園共有。轉載時必須保留此段聲明,且在文章頁面明顯位置給出原文連接地址! |

浙公網安備 33010602011771號