为什么我不能将此条目添加到我的字典中?

时间:2014-10-29 00:12:15

标签: c# winforms list object dictionary

我正在尝试创建一个通过文本框获取和输入URL的应用程序,在单击按钮时检索该网站的HtmlCode并将其存储在字典中,然后显示在列表框中。

但是,由于在尝试向词典添加条目时遇到问题,我还没有能够将其中任何一个实现到用户界面中。要检索HtmlCode,我正在调用方法GetHtml,但是,当我尝试将网站和代码添加到字典时,我收到错误。

代码遵循

namespace HtmlCheck
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());

            var dict = new SortedDictionary<string, WebsiteInfo>();

            var list = (from entry in dict
                        orderby entry.Key
                        select entry.Key).ToList();

        }

        private static void addPerson(string websiteUrl)
        {
            dict.Add(websiteUrl, new WebsiteInfo { WebsiteUrl = websiteUrl, HtmlCode = getHtml(websiteUrl) });
        }

        private static SortedDictionary<string, WebsiteInfo> dict;

        public string getHtml(string websiteUrl)
        {
            using (WebClient client = new WebClient())
                return client.DownloadString(websiteUrl);
        }
    }

    public class WebsiteInfo
    {
        public string WebsiteUrl;
        public string HtmlCode;

        public override string ToString()
        {
            string formated = string.Format("{0}\n---------------------------------- \n{1}", WebsiteUrl, HtmlCode);
            return formated;
        }
    }
}

方法

        private static void addPerson(string websiteUrl)
        {
            dict.Add(websiteUrl, new WebsiteInfo { WebsiteUrl = websiteUrl, HtmlCode = getHtml(websiteUrl) });
        }

HtmlCode = getHtml(websiteUrl)抛出错误:

"An object reference is required for the non-static field, method, or property 'HtmlCheck.Program.getHtml(string)'"

所以我的问题是,为什么我不能用这些信息在字典中添加一个条目?

感谢您的时间。

3 个答案:

答案 0 :(得分:4)

您收到该错误是因为addPerson()是一个静态方法(在没有创建Program类的实例的情况下调用它),但getHtml()方法不是 static(所以你需要一个Program类的实例来调用它。)

轻松修复 - 使其静止:

public static string getHtml(string websiteUrl)
{
    ...
}

为了完整起见,在调用Program方法之前,您必须以其他方式创建getHtml()类的实例:

private static void addPerson(string websiteUrl)
{
    var p = new Program();
    dict.Add(websiteUrl, new WebsiteInfo { WebsiteUrl = websiteUrl, HtmlCode = p.getHtml(websiteUrl) });
}

答案 1 :(得分:1)

在方法中添加“static”;

        public static string getHtml(string websiteUrl)

答案 2 :(得分:1)

addPerson()静态方法,这意味着您可以随时调用它,而无需使用类的实例来调用它。然后它尝试调用getHtml(),这是非静态,这意味着它只能通过类的有效实例调用。

我建议你对C#中的静态方法进行一些研究,以了解这一点。

相关问题