本文共 966 字,大约阅读时间需要 3 分钟。
------------StringHelper.cs-------------
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions;
//声明扩展方法的步骤:类必须是static,方法是static, //第一个参数是被扩展的对象,前面标注this。 //使用扩展方法的时候必须保证扩展方法类已经在当前代码中usingnamespace 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 = ""; //这里就可以直接使用string类的扩展方法IsEmail了 Console.WriteLine(_myEmail.IsEmail()); //调用接收参数的扩展方法 Console.WriteLine(_myEmail.Quot("!")); Console.ReadLine(); } } }转载地址:http://ftnmb.baihongyu.com/