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

查看:45
本文介绍了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"

下面的语句将点击每个网址.

The below statement will click on each url.

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

我想一一点击这些网址.所以我使用了 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天全站免登陆