【发布时间】:2014-12-24 14:07:39
【问题描述】:
我正在尝试制作一个应用程序,该应用程序通过文本框获取和输入 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)'"
所以我的问题是,为什么我不能在字典中添加包含这些信息的条目?
感谢您的宝贵时间。
【问题讨论】:
-
getHtml 不是静态方法。所以你需要构造一个 Program 对象来调用它。我认为您只想在该方法中添加静态关键字。
标签: c# winforms list object dictionary