class UsingStreamUtilWithoutExtensions
{
static void Main() //使用StreamUtil 来拷贝网络响应流到一个文件
{//将Web响应写入磁盘
WebRequest request = WebRequest.Create("http://manning.com");
using (WebResponse response = request.GetResponse())
//响应流(response stream)索取更多的数据,直至接收到所有数据
using (Stream responseStream = response.GetResponseStream())
using (FileStream output = File.Create("response.dat"))
{
StreamUtilNoExtensions.Copy(responseStream, output);
//调用 StreamUtilNoExtensions的 Copy方法
}
}
}
public static class StreamUtilNoExtensions //为流提供附加功能的一个简单的工具类 没用扩展方法
{
const int BufferSize = 8192;
public static void Copy(Stream input,
Stream output)
{
byte[] buffer = new byte[BufferSize];//最大8192
int read;//read最大8192,也可以小于8192
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
public static byte[] ReadFully(Stream input)
{
using (MemoryStream tempStream = new MemoryStream())
{
Copy(input, tempStream);
if (tempStream.Length == tempStream.GetBuffer().Length)
{
return tempStream.GetBuffer();
}
return tempStream.ToArray();
}
}
}
扩展方法创建起来非常容易,使用起来也很简单。
声明扩展方法
并不是任何方法都能作为扩展方法使用--它必须具有以下特征:
它必须在一个非嵌套的、非泛型的静态类中(所以必须是一个静态方法)
它至少要有一个参数
第一个参数必须附加this 关键字作为前缀
第一个参数不能有其他任何修饰符(比如out或ref)
第一个参数的类型不能是指针类型
这个是没有使用扩展方法的
输出
response.dat 231kb