繁体   English   中英

C# - 访问变量动态命名

[英]C# - Access variable Names dynamically

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

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

以下语句将点击每个网址。

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);
}

您可以将所需的所有链接存储到类型的Coolection中: IList<Link>IEnumerable<Link>

IList<Link> myCollection = new List<Link>();

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM