2012-09-26 85 views
0

我是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;那麼變量是正確的但沒有返回它。 這可能是非常明顯的,有人可以解釋爲什麼它不工作,以及如何解決它?

謝謝

+5

嘗試使用該值而不是立即退出該方法。如果未使用,優化版本不會保存返回值。 –

+1

我剛試過這個,它在這臺機器上工作..? – Thousand

+0

@奧斯汀薩隆 - 感謝就是這樣。我在一個臨時行'string pause;'上放了一個斷點,並進行了檢查。如果我真的使用這個變量,那麼它就有一個值。這有點煩人!這種行爲是否有任何理由?如果您添加該答案,我會接受。 – user3357963

回答

1

嘗試使用該值而不是立即退出該方法。如果未使用,優化版本不會保存返回值。

+0

謝謝 - 我現在發現了一個理由,爲什麼在Debug配置而不是Release下開始調試更好? – user3357963

1

無需這樣的:

StringBuilder htmlString = new StringBuilder(); 
htmlString = htmlReq.getHtml(uri); 

這足以說:

StringBuilder htmlString = htmlReq.getHtml(uri); 

你必須定義什麼。沒有什麼意思是「空」,「垃圾」,什麼? htmlString是過去的對象嗎?或者,也許該功能根本不返回?它是什麼?

+0

謝謝馬呂斯 - 我原本有你的建議,但在調試時改變了它。 – user3357963

相關問題