标签:静态 new 了解 none where 理念 src copy web
C#3 引入的扩展方法这一个理念.
扩展方法最明显的特征是在方法参数中第一个参数有this声明. 其实C#库中有很多已经是扩展方法了.比如linq中对序列使用的查询语句, where, select等都是经过扩展的方法.
由于有很多抽象的方法, 比如stream这种, 在很多继承类里面没有完全的达到使用者的目的, 使用者往往需要自己写一个工具类, 例如StreamUtil来维护所有的继承类, 一般这种工具类都是静态的. C#3可以使用扩展方法来改进这一需求的实现.
例如代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.IO; 7 8 namespace DennisDemos.Demos 9 { 10 public static class StreamUtil 11 { 12 const int BufferSize = 8192; 13 public static void Copy(Stream input, Stream output) 14 { 15 byte[] buffer = new byte[BufferSize]; 16 int read; 17 while ((read = input.Read(buffer,0,buffer.Length)) > 0) 18 { 19 output.Write(buffer, 0, read); 20 } 21 } 22 public static byte[] ReadFully(Stream input) 23 { 24 using (MemoryStream ms = new MemoryStream()) 25 { 26 Copy(input, ms); 27 return ms.ToArray(); 28 } 29 } 30 } 31 }
1 WebRequest request = WebRequest.Create("http://www.baidu.com"); 2 using (WebResponse response = request.GetResponse()) 3 using (Stream responseStream = response.GetResponseStream()) 4 using (FileStream output = File.Create("response.dat")) 5 { 6 StreamUtil.Copy(responseStream, output); 7 }
了解扩展方法的使用时机以及方式
并不是所有方法都可以作为扩展方法使用, 他必须具备以下特征:
1. 必须在一个非嵌套的, 非泛型的静态类中(所以必须是一个静态方法)
2. 至少要有一个参数
3. 第一个参数必须附加this
4. 第一个参数不能有其他任何修饰符, 比如ref
5. 第一个参数的类型不能使指针类型.
这里第一个参数的类型成为方法的扩展类型.
标签:静态 new 了解 none where 理念 src copy web
原文地址:https://www.cnblogs.com/it-dennis/p/9174299.html