0

私はC#を初めて使用し、以下のコードが機能しない理由を理解しようとしています。静的ではないカスタムクラスHtmlRequestを作成しようとしたので、を使用して必要な回数だけインスタンス化できますHtmlRequest someVar = new HtmlRequest();

hmtmlStringreturn sbは値を保持していますが、行に戻されていません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

メソッドをすぐに終了するのではなく、値を使用してみてください。最適化されたビルドは、使用されていない場合、戻り値を保存しません。

于 2012-09-26T20:21:18.067 に答える
1

これは必要ありません:

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

言うだけで十分です:

StringBuilder htmlString = htmlReq.getHtml(uri);

何も定義する必要はありません。「ヌル」、「ゴミ」という意味は何もありません、何ですか?htmlStringは以前のオブジェクトですか?それとも、関数がまったく返されないのでしょうか。それは何ですか?

于 2012-09-26T20:14:23.953 に答える