[英]call a non extension method defined inside non static class from Main() c#
我嘗試從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()方法。 如何在代碼中調用已定義的方法? 請幫我。
謝謝。
如何在代碼中調用已定義的方法?
只是不要在流上調用它(這使其看起來像實例方法)。 將其作為普通的靜態方法調用,並具有與兩個參數相對應的兩個參數:
CopyTo(webResponse.GetResponseStream(), ms);
不能在實例上調用非擴展靜態方法。 您可以僅使用簡單名稱,也可以使用類型名稱( Get.CopyTo(...)
)對其進行限定。
目前尚不清楚,如果您使用的是.NET 4+,但支持CopyTo
則為什么要使用此功能。
如果我對您的問題的理解正確,那么您想創建一種擴展方法,將該方法復制到另一個流中。 要定義擴展方法,請使用
public static class myExtensions
{
public static void myCopyTo(this Stream input, Stream output)
{
// your code goes here
}
}
然后可以通過以下方式調用它:
webResponse.GetResponseStream().myCopyTo(ms);
筆記:
this
作為第一個參數。 此參數表示您要擴展的類的類型。 CopyTo
方法沖突 希望對您有所幫助。 如果您需要其他任何提示,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.