简体   繁体   English

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

[英]Use the Extension method instead Built-in method in C#

Some Built-in methods are not working for me, I' m using old version of .NetFramework for my application which is not having some new methods. 一些内置方法不适用于我,我正在为我的应用程序使用旧版本的.NetFramework,而该版本没有一些新方法。 So, I' m trying to create extension methods that overrides the built-in methods. 因此,我正在尝试创建扩展方法,以覆盖内置方法。 But I' m facing some issues with. 但是我面临一些问题。 Here is the code: 这是代码:

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

}//end name space } //结束名称空间

The errors I' m getting are 我得到的错误是

1) Extension methods must be defined in a top level static class; 1)扩展方法必须在顶级静态类中定义; 'Retrive' is a nested class . “检索”是一个嵌套类。

I don' t understand why 'Retrieve' class became nested. 我不明白为什么“检索”类被嵌套。

2) Extension methods must be defined in a non-Generic static class 2)扩展方法必须在非泛型静态类中定义

How to solve these issues? 如何解决这些问题? Please help me. 请帮我。

Thank you. 谢谢。

non generic static class means you are creating a class that is not using template. 非通用静态类意味着您正在创建不使用模板的类。

eg List is a generic class but MemoryStream or alot of class are not generic. 例如List是一个通用类,但是MemoryStream或很多类不是通用的。

nested class answer is already given in this thread. 这个线程已经给出了嵌套类的答案。

Try keeping "static void Main()" in any other class. 尝试在任何其他类中保留“ static void Main()”。 I mean other than the one you are trying to use for creating extensions. 我的意思是,除了您尝试用于创建扩展的那个。

It looks like your main methods is also in the Retriev class. 看来您的主要方法也位于Retriev类中。 I recommand to create a seperate class for extensions methods as shown below: 我建议为扩展方法创建一个单独的类,如下所示:

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);
    }
  }  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM