1

我尝试从 Main() 调用静态类下定义的 Extension 方法,它起作用了。现在我想在我的应用程序中使用它,为此我需要将扩展​​方法设为静态方法(因为我的应用程序中没有定义静态类)并从 Main() 调用它。

这是我正在尝试的:

public class Get 
{  
     public static void CopyTo(Stream input, Stream output) //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 ()
    {
              ////I' m just mentioning a small part of my code
              ////Please ignore about the variables(url, baseURL,authenticatestr...) those are not declared here, they have been declared at some other part in the code
            /////Here in the main method I have a call to the above method

       HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
       request = (HttpWebRequest)WebRequest.Create (baseURL + uri);
       request.Headers.Add ("Authn", authenticateStr);
       request.Accept = "";
       request.Method = "GET";
       webResponse = (HttpWebResponse)request.GetResponse();
       using (MemoryStream ms = new MemoryStream())
       using (FileStream outfile = new FileStream("1" , FileMode.Create)) {
           webResponse.GetResponseStream().CopyTo(ms);///Here I need to call my method                                                                      
           outfile.Write(ms.GetBuffer(), 0, (int)ms.Length);
                }

但这仍在尝试调用 .NetFramework CopyTo() 方法。如何调用代码中定义的方法?请帮我。

谢谢你。

4

2 回答 2

6

如何调用代码中定义的方法?

只是不要流上调用它(这使它看起来像一个实例方法)。将其作为普通静态方法调用,两个参数对应于两个参数:

CopyTo(webResponse.GetResponseStream(), ms);

永远不能在实例上调用非扩展静态方法。您可以只使用简单名称,也可以使用类型名称 ( Get.CopyTo(...)) 对其进行限定。

CopyTo如果您使用的是受支持的 .NET 4+,则不清楚为什么要使用它。

于 2013-04-29T06:18:37.430 回答
1

如果我理解你的问题是正确的,你想创建一个扩展方法,将一个流复制到另一个流中。要定义扩展方法,请使用

public static class myExtensions
{
     public static void myCopyTo(this Stream input, Stream output)
     {
        // your code goes here
     }
}

然后你可以通过以下方式调用它:

webResponse.GetResponseStream().myCopyTo(ms);

笔记:

  • 包含扩展方法的类必须是静态的,并且必须是顶级类。
  • 扩展方法也必须是静态的,它必须包含关键字作为this第一个参数。此参数表示您要扩展的类的类型。
  • 我已重命名您的方法以避免与现有 .NET 框架的CopyTo方法发生冲突

我希望这会有所帮助。如果您需要任何其他提示,请告诉我。

于 2013-04-29T06:37:56.280 回答