0

我是 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;那么变量是正确的,但没有返回它。这可能是非常明显的事情,有人可以解释为什么它不起作用以及如何解决它吗?

谢谢

4

2 回答 2

1

不需要这个:

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

说一句就够了:

StringBuilder htmlString = htmlReq.getHtml(uri);

你不必定义任何东西。没有什么意思是“空”,“垃圾”,什么?htmlString 是它以前的对象吗?或者函数根本不返回?它是什么?

于 2012-09-26T20:14:23.953 回答
1

尝试使用该值而不是立即退出该方法。如果不使用,优化的构建将不会保存返回值。

于 2012-09-26T20:21:18.067 回答