我是C#的新手,並試圖讓我的頭腦爲什麼下面的代碼不工作。我試圖做一個自定義類HtmlRequest不是靜態的,所以可以作爲使用HtmlRequest someVar = new HtmlRequest();
從另一個類的方法返回一個變量
回報某人持有的價值,但它在返回hmtmlString
上線htmlString = htmlReq.getHtml(uri)
需要被實例化多次。
我試圖把獲取{代碼...回報SB;} public類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;
那麼變量是正確的但沒有返回它。 這可能是非常明顯的,有人可以解釋爲什麼它不工作,以及如何解決它?
謝謝
嘗試使用該值而不是立即退出該方法。如果未使用,優化版本不會保存返回值。 –
我剛試過這個,它在這臺機器上工作..? – Thousand
@奧斯汀薩隆 - 感謝就是這樣。我在一個臨時行'string pause;'上放了一個斷點,並進行了檢查。如果我真的使用這個變量,那麼它就有一個值。這有點煩人!這種行爲是否有任何理由?如果您添加該答案,我會接受。 – user3357963