扩展方法

1、扩展方法必须写在静态类中

2、扩展方法也必须是静态方法

3、方法参数第一个为需要添加静态方法的类

 

//1.扩展方法必须写到静态类中。
static class StringExt
{
//2.扩展方法也必须是静态方法
//第一个参数表示要给哪个类型增加一个扩展方法 this 类型 变量
public static bool IsEmail(this string emailStr)
{
return Regex.IsMatch(emailStr, @"^\w+@\w+\.\w+$");
}


public static bool IsPostcode(this string postStr)
{
return Regex.IsMatch(postStr, @"^\d{6}$");
}

public static void SayHi(this Person p)
{
//扩展方法是不能访问原来类中的私有成员的。
Console.WriteLine("大家好,我是:{0}", p.Name);
}

public static void SayHello(this Person p, string msg, int n)
{
Console.WriteLine("{0}--{1}", msg, n);
}

}

 

 

 

用方式:

 

 

class Program
{
static void Main(string[] args)
{
string str = "zxh@itcast.cn";

string str1 = "100193";

if (str.IsEmail())
{
Console.WriteLine("yes");
}
else
{
Console.WriteLine("no");
}
Console.ReadKey();

//if (str1.IsPostcode())
//{

//}


int[] arrInt = new int[] { 1, 2, 32 };
// arrInt.Count(
Person p = new Person();
p.Name = "zxh";
p.SayHi();
p.SayHello("aaaaaaaa", 1000);
Console.ReadKey();
}
}
public class Person
{
public void Test1()
{
score = 10;
}

private int score;

public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
public string Email
{
get;
set;
}

}

 

  扩展方法

1)        扩展方法声明在静态类中,定义为一个静态方法,其第一个参数需要使用this关键字标识,指示它所扩展的类型。

2)  扩展方法可以将方法写入最初没有提供该方法的类中。还可以把方法添加到实现某个接口的任何类中,这样多个类就可以使用相同的实现代码。(LINQ中,System.Linq.Queryable.cs和System.Linq.Enumerable.cs 正是对接口添加扩展方法)

3)        扩展方法虽定义为一个静态方法,但其调用时不必提供定义静态方法的类名,只需引入对应的命名空间,访问方式同实例方法。

4)        扩展方法不能访问它所扩展的类型的私有成员。

posted on 2014-06-05 22:27  蒲苇吥弃  阅读(136)  评论(0编辑  收藏  举报

导航