简体   繁体   中英

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. 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; '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

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.

nested class answer is already given in this thread.

Try keeping "static void Main()" in any other class. 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. 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);
    }
  }  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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