C# – 访问变量动态命名

我正在自动化网页。 我已经捕获并保存了文件中的链接。

Link Url_0="gmail.com" Link Url_1="ymail.com" Link Url_2="hotmail.com" Link Url_3="outlook.com" 

以下语句将点击每个url。

 HomePage.Url_0.Click();//Homepage is the Class name 

我想逐个点击这些url。 所以我使用for循环。

 for(int i=0;i<3;i++) { String url=String.Format("Url_{0}",i); HomePage.url.Click(); //This is throwing me error (I think that this is not correct way to do.) Sleep(2000); } 

我该怎么办? 这可以以任何方式完成吗? 任何帮助表示赞赏。

您应该将变量放入集合中,而不是让每个变量具有不同的名称。 从技术上讲,可以在你描述的庄园中访问变量,但这并不是像C#这样的语言设计的,而且是非常糟糕的练习。

有几个集合可供选择。 这里的List可能是合适的,数组也可以工作。

 List urls = new List() { "gmail.com", "ymail.com", "hotmail.com", "outlook.com" }; foreach (string url in urls) { //do whatever with the url Console.WriteLine(url); } 

您可以将所需的所有链接存储到类型的Coolection中: IListIEnumerable

 IList myCollection = new List(); 

在那之后,你将通过一个项目进入集合中的项目

 foreach(var item in myCollection ) { //Here implement your logic with click }