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