我正在自动化网页。我已捕获链接并将其保存在文件中。
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
我想一个一个地点击这些网址。所以我正在使用 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<string> urls = new List<string>()
{
"gmail.com",
"ymail.com",
"hotmail.com",
"outlook.com"
};
foreach (string url in urls)
{
//do whatever with the url
Console.WriteLine(url);
}
关于C# - 动态访问变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13705577/