2012-09-26 84 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

相关问题