[英]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.