给string定义一个扩展方法

 创建一个 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();

}

}

}

原文地址:https://www.cnblogs.com/workstation-nigoudongma/p/9528583.html