C#扩展方法ExtendsMethod

本文介绍了如何在不改变原有类的基础上为类添加方法,通过定义静态扩展方法,可以为特定类型的对象提供额外的功能。以string和People类为例,展示了如何实现扩展方法,并在代码中进行了实践演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在不更改原来类的基础山,为类添加方法。
  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 }

 

转载于:https://www.cnblogs.com/QLJ1314/archive/2012/08/04/ExtendsMethod.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值