您的位置:首页 > 其它

string扩展方法使用

2011-12-28 23:46 260 查看
创建一个 static 的类,并且里面的方法也必须是static的,第一个参数是被扩展的对象,必须标注为this,使用时,必须保证namespace using进来了.

下面为实例:



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

namespace stringHelper扩展方法1
{
    static class StringHelper
    {
        public static bool IsEmail(this string s)
        {
            if (s.Contains("@"))
            {
                return true;
            }else return false;
        }

        public static string FKH(this string s)
        {
            return "[" + s + "]";
        }

    }
}


调用



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using stringHelper扩展方法1;

namespace stringHelper扩展方法
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入一个Email邮箱");
            string s = Console.ReadLine();
            bool b= s.IsEmail();
            if (b)
            {
                Console.WriteLine("是正确邮箱");
            }
            else
            {
                Console.WriteLine("不是正确的邮箱");
            }
            Console.WriteLine(s.FKH().FKH().FKH().FKH());
            Console.ReadKey();
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: