C#-动态访问变量名称 [英] C# - Access variable Names dynamically

查看:174
本文介绍了C#-动态访问变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am automating a web page. i have captured and saved the Links in a file.

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

下面的语句将单击每个URL.

The below statement will click on each url.

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

我想要一个一个地单击这些URL.所以我在用for循环.

I want to Click these URLs one by one. So I am using a for loop.

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

我该如何进行?可以以任何方式完成此操作吗?感谢您的帮助.

How can I proceed here ? Can this be done in any way ? Any help is appreciated.

推荐答案

您应该将变量放入集合中,而不要使用其他名称不同的不同变量.从技术上讲,可以在您描述的庄园中访问变量,但这不是C#之类的语言设计的目的,并且非常是一种不好的做法.

You should put the variables into a collection, rather than having a different variable with a different name for each. It's technically possible to access the variable in the manor you describe, but it's not what a language like C# is designed to do, and would be very bad practice.

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

There are several collections to choose from. Here a List is probably appropriate, an array could work as well.

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#-动态访问变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆