【发布时间】:2012-09-27 04:23:57
【问题描述】:
我是 C# 新手,想弄清楚为什么下面的代码不起作用。我尝试制作一个非静态的自定义类 HtmlRequest,因此可以使用 HtmlRequest someVar = new HtmlRequest();
return sb 持有该值,但它没有返回到 htmlString = htmlReq.getHtml(uri) 行上的 hmtmlString。
我尝试将 Get{code ...return sb;} 放在公共类 HtmlRequest 之后,但无法获得正确的语法
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; 上设置断点,那么变量是正确的,但不会返回它。
这可能很明显,有人可以解释为什么它不起作用以及如何解决它吗?
谢谢
【问题讨论】:
-
尝试使用该值而不是立即退出该方法。如果不使用,优化的构建将不会保存返回值。
-
我刚试过这个,它可以在这台机器上运行..?
-
@AustinSalonen - 谢谢。我在临时行
string pause;上放了一个断点并检查。如果我实际使用该变量,那么它就有一个值。这有点烦人!这种行为有什么原因吗?如果您将其添加为答案,我会接受。
标签: c#