【问题标题】:C# - Access variable Names dynamicallyC# - 动态访问变量名称
【发布时间】:2012-11-22 05:40:51
【问题描述】:

我正在自动化网页。我已将链接捕获并保存在一个文件中。

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# .net user-interface automation


【解决方案1】:

您应该将变量放入一个集合中,而不是为每个变量使用不同的名称。从技术上讲,访问您描述的庄园中的变量是可行的,但这不是像 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);
}

【讨论】:

  • 当然,List&lt;string&gt; 不是一个数组——它是一个字符串列表。
  • @tomfanning 这是一个数组的包装器。你可以把它想象成一个数组,但你是对的,我会编辑它。
【解决方案2】:

您可以将所有链接存储到 Coolection 类型:IList&lt;Link&gt;IEnumerable&lt;Link&gt;

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

之后,您将使用

浏览集合中的项目
foreach(var item in myCollection ) {
      //Here implement your logic with click
}

【讨论】:

  • 你不能 newIList
  • @Servy - 是的..我想念那个。应该是IList&lt;Link&gt; myCollection = new List&lt;Link&gt;(); 谢谢
猜你喜欢
  • 1970-01-01
  • 2015-05-24
  • 2022-04-26
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
  • 2018-09-26
  • 1970-01-01
  • 2014-09-17
相关资源
最近更新 更多