C# 擴展系統類string的方法

------------StringHelper.cs-------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;


//聲明擴展方法的步驟:類必須是static,方法是static,
//第一個參數是被擴展的對象,前面標註this。
//使用擴展方法的時候必須保證擴展方法類已經在當前代碼中using

namespace CLeopard.SystemEx
{
    //擴展方法必須是靜態的
    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;
        }
    }
}

 

------------Program.cs-------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CLeopard.SystemEx
{
    class Program
    {
        static void Main(string[] args)
        {
            string _myEmail = "[email protected]";
            //這裏就可以直接使用string類的擴展方法IsEmail了
            Console.WriteLine(_myEmail.IsEmail());
            //調用接收參數的擴展方法
            Console.WriteLine(_myEmail.Quot("!"));


            Console.ReadLine();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章