我是 C# 的新手,并试图弄清楚为什么下面的代码不起作用。我尝试制作一个非静态的自定义类 HtmlRequest,因此可以根据需要使用HtmlRequest someVar = new HtmlRequest();
return sb 持有该值,但它没有被返回到hmtmlString
线上htmlString = htmlReq.getHtml(uri)
。
我尝试在公共类 HtmlRequest 之后放置 Get{code ...return sb;} 但无法获得正确的语法
public partial class MainWindow : DXWindow
{
private void GetLinks()
{
HtmlRequest htmlReq = new HtmlRequest();
Uri uri = new Uri("http://stackoverflow.com/");
StringBuilder htmlString = new StringBuilder();
htmlString = htmlReq.getHtml(uri); //nothing returned on htmlString
}
}
public class HtmlRequest
{
public StringBuilder getHtml(Uri uri)
{
// used to build entire input
StringBuilder sb = new StringBuilder();
// used on each read operation
byte[] buf = new byte[8192];
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
// execute the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
Do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?
return sb;
}
}
如果我在上面设置断点,return sb;
那么变量是正确的,但没有返回它。这可能是非常明显的事情,有人可以解释为什么它不起作用以及如何解决它吗?
谢谢