C#扩展方法ExtendsMethod

在不更改原来类的基础山,为类添加方法。
  1,扩展方法必须写静态类中
  2,扩展方法必须是静态方法,虽然是静态方法,但是这个扩张方法是为对象扩展的,只能由对象调用。
  public static class 类名
  {
 public static 返回值 方法名(this 要扩展的类型 对象名[,参数列表])
 {

 }

  }   /*
  this string ss
  这个参数只起到一个说明性作用。
  这个扩展方法是为string的对象扩展的,只能有string得对象来使用
  str值得是使用这个扩展方的对象。
  */

下面我们看段代码练习....

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 public class StudyExtendMethod
 5 {
 6     public static void Main()
 7     {
 8         string file =  @"E:\FTPPUBLISH\学习资料\KindEditor\kindeditor-v4.0.3\examples\colorpicker.html";
 9         Console.WriteLine(file.GetFileType());
10         string  sss = "78.9.09.mp3";
11         Console.WriteLine(sss.GetFileType());
12         People pp = new People();
13         pp.WatchTime("www");
14         string od = pp.GetInfo("张三");
15         Console.WriteLine(od);
16         List<int> list = new List<int>();
17         list.Add(1);
18         list.Add(19);
19         list.Add(34);
20         list.Add(56);
21         list.Add(2);
22         list.Add(90);
23         list.Add(23);
24         list.Add(27);
25         var c = list.GetBigTen(10);
26         foreach(int d in c)
27         {
28             Console.WriteLine(d);
29         }
30 
31     }
32 }
33 public static class ExtendMethod
34 {
35     /*
36         this string ss
37         这个参数只起到一个说明性作用。
38         这个扩展方法是为string的对象扩展的,只能有string得对象来使用
39         str值得是使用这个扩展方的对象。
40     */
41     public static string GetFileType(this string str)
42     {a
43         string[] strs = str.Split('.');
44         return strs[strs.Length-1];
45     }
46     public static void WatchTime(this People p,string name)
47     {
48         Console.WriteLine(name +"  "+DateTime.Now);
49     }
50     public static string GetInfo(this People p,string name)
51     {
52         return name+"sssss";
53     }
54     public static IEnumerable<int> GetBigTen(this List<int> list,int a)
55     {
56         return list.Where(p=>p>a);
57     }
58 }
59 public class People
60 {
61 
62 }

 

posted @ 2012-08-04 14:10  妍珊  阅读(3202)  评论(0编辑  收藏  举报