【问题标题】:Return a variable from method in another class从另一个类中的方法返回一个变量
【发布时间】:2012-09-27 04:23:57
【问题描述】:

我是 C# 新手,想弄清楚为什么下面的代码不起作用。我尝试制作一个非静态的自定义类 HtmlRequest,因此可以使用 HtmlRequest someVar = new HtmlRequest();

根据需要实例化任意多次

return sb 持有该值,但它没有返回到 htmlString = htmlReq.getHtml(uri) 行上的 hmtmlString

我尝试将 Get{code ...return sb;} 放在公共类 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; 上设置断点,那么变量是正确的,但不会返回它。 这可能很明显,有人可以解释为什么它不起作用以及如何解决它吗?

谢谢

【问题讨论】:

  • 尝试使用该值而不是立即退出该方法。如果不使用,优化的构建将不会保存返回值。
  • 我刚试过这个,它可以在这台机器上运行..?
  • @AustinSalonen - 谢谢。我在临时行string pause; 上放了一个断点并检查。如果我实际使用该变量,那么它就有一个值。这有点烦人!这种行为有什么原因吗?如果您将其添加为答案,我会接受。

标签: c#


【解决方案1】:

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

【讨论】:

  • 谢谢 - 我现在发现了一个原因,为什么最好在 Debug 配置而不是 Release 中开始调试!
【解决方案2】:

不需要这个:

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

这样说就够了:

StringBuilder htmlString = htmlReq.getHtml(uri);

您无需定义任何内容。没有什么意思是“空”,“垃圾”,什么? htmlString 是它以前的对象吗?或者函数根本不返回?这是什么?

【讨论】:

  • 感谢 Marius - 我最初确实有您的建议,但在调试时更改了它。
猜你喜欢
  • 1970-01-01
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 2014-10-10
相关资源
最近更新 更多