1、聲明擴展方法的步驟:類必須是static,方法是static
2、第一個參數是被擴展的對象,前面標注this
3、使用擴展方法的時候必須保證擴展方法類已經在當前代碼中using
例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions;
namespace CLeopard.SystemExt { //擴展方法必須是靜態的 public static class StringHelper { //擴展方法必須是靜態的,第一個參數必須加上this public static bool IsEmail(this string _input) { return Regex.IsMatch(_input, @"^\w+@\w+\.\w+$"); } //帶多個參數的擴展方法 //在原始字符串前后加上指定的字符 public static string Quot(this string _input, string _quot) { return _quot + _input + _quot; } } } 使用: string _myEmail = "test@163.com"; //這里就可以直接使用string類的擴展方法IsEmail了 Console.WriteLine(_myEmail.IsEmail()); //調用接收參數的擴展方法 Console.WriteLine(_myEmail.Quot("!"));
以上是基於擴展類的動態,那么靜態方法如何去擴展,經過研究,C#4.0的語法沒辦法時間,不排除以后會出現實現方式,只能是普通建另一個類來做。