[英]Use the Extension method instead Built-in method in C#
一些內置方法不適用於我,我正在為我的應用程序使用舊版本的.NetFramework,而該版本沒有一些新方法。 因此,我正在嘗試創建擴展方法,以覆蓋內置方法。 但是我面臨一些問題。 這是代碼:
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)擴展方法必須在頂級靜態類中定義; “檢索”是一個嵌套類。
我不明白為什么“檢索”類被嵌套。
2)擴展方法必須在非泛型靜態類中定義
如何解決這些問題? 請幫我。
謝謝。
非通用靜態類意味着您正在創建不使用模板的類。
例如List是一個通用類,但是MemoryStream或很多類不是通用的。
這個線程已經給出了嵌套類的答案。
嘗試在任何其他類中保留“ static void Main()”。 我的意思是,除了您嘗試用於創建擴展的那個。
看來您的主要方法也位於Retriev類中。 我建議為擴展方法創建一個單獨的類,如下所示:
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.