在c#中使用扩展方法代替内置方法

本文关键字:方法 内置 扩展 | 更新日期: 2023-09-27 18:10:32

一些内置方法不适合我,我使用旧版本的。net framework为我的应用程序,这是没有一些新的方法。因此,我尝试创建覆盖内置方法的扩展方法。但我遇到了一些问题。下面是代码:

using System; 
using System.IO; 
using System.Net;
using System.Xml;
using System.Text;  
using System.Collections.Generic;
namespace API{
public static class Retrive 
{               
    // some variables
    public static void CopyTo(this Stream input, Stream output)///Extension method
    {
        byte[] buffer = new byte[32768];  
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write (buffer, 0, read);
        }
    }   
    public static void Main ()
    {
          string url = "https://";          
          string baseURL = "";   
          string authenticateStr = "";
        try 
        {
            ///
            }

        catch (WebException e) 
        {
            using (WebResponse response = e.Response) 
            {
                ////
            }
        }
    }  // end main()
}  // end class

}//结束名称空间

我得到的错误是

1)扩展方法必须在顶层静态类中定义;"检索"是一个嵌套类。

我不明白为什么'Retrieve'类会嵌套。

2)扩展方法必须在非泛型静态类 中定义

如何解决这些问题?请帮帮我。

谢谢。

在c#中使用扩展方法代替内置方法

非泛型静态类意味着你正在创建一个不使用模板的类。

。List是一个泛型类,但MemoryStream或许多类不是泛型的。

嵌套类的答案已经在这个线程中给出了

尝试在任何其他类中保持"static void Main()"。

看起来您的主方法也在retriv类中。我建议为扩展方法创建一个单独的类,如下所示:

public static class ExtMethods 
{
  public static void CopyTo(this Stream input, Stream output)///Extension method
  {
    byte[] buffer = new byte[32768];  
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
       output.Write (buffer, 0, read);
    }
  }  
}