C# 擴展系統類方法


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的語法沒辦法時間,不排除以后會出現實現方式,只能是普通建另一個類來做。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM