我有以下代码,这是一组重复20次的错误:
WebBrowserJobs wb1 = new WebBrowserJobs();
Uri uri1 = new Uri("https://www.site1.it");
wb1.Url = uri1;
wb1.DocumentCompleted+= new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
WebBrowserJobs wb2 = new WebBrowserJobs();
Uri uri2 = new Uri("https://www.site2.it");
wb2.Url = uri2;
wb2.DocumentCompleted+= new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
...................
...................
...................
WebBrowserJobs wb20 = new WebBrowserJobs();
Uri uri20 = new Uri("https://www.site20.it");
wb20.Url = uri20;
wb20.DocumentCompleted+= new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
代码工作正常但每次我必须添加一个新网站废弃,我必须编辑代码......
我不知道是否有可能(以及如何)根据包含网址列表的简单字符串列表创建一种迭代。
可能重构库对这项工作有用吗?
由于
答案 0 :(得分:4)
var mySites = new []{"http://site1.com", "http://site2.com"};
foreach(var site in mySites)
{
WebBrowserJobs wb = new WebBrowserJobs { Url = new Uri(site) };
wb.DocumentCompleted+= new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
}
这应该有用。
答案 1 :(得分:1)
如果您需要确保 all:
A=$$(stat -c %Y test1);\
echo "A is $$A";\
touch test1;\
B=$$(stat -c %Y test1);\
echo "B is $$B";\
if (($$A<$$B)); then echo true; fi
对象保留在范围内并且不收集/处置垃圾,那么您可以做一些简单的事情。首先是建立工作的方法:
WebBrowserJobs
你这样称呼它:
public WebBrowserJobs CreateBroswerJob(string url)
{
var wb = new WebBrowserJobs();
wb.Url = new Uri(url);
wb.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
return wb;
}
现在您有一个作业对象的集合,您可以查询或循环并根据需要执行某些操作。
额外奖励:你可以用一些Linq简化//Your list of sites, add to this when necessary
var urls = new List<string>
{
"https://www.site1.it",
"https://www.site2.it",
"https://www.site3.it"
}
var jobs = new List<WebBrowserJobs>();
foreach (var url in urls)
{
jobs.Add(CreateBroswerJob(url));
}
:
foreach
答案 2 :(得分:-3)
foreach (var str in collection)
{
WebBrowserJobs wb1 = new WebBrowserJobs();
Uri uri1 = new Uri(str);
wb1.Url = uri1;
wb1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
}