【发布时间】:2017-12-11 18:29:04
【问题描述】:
我正在学习 c# 并试图了解数组。我在 selenium c# 中实际使用数组并面临一种情况,我无法将它们的值迭代存储到数组中。我的意图是,我想存储数组中的所有价格,然后用for循环在控制台中一一迭代。
namespace OneDimensionalarray
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = null;
driver = new ChromeDriver();
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
driver.Navigate().GoToUrl("http://www.shopclues.com/");
driver.FindElement(By.XPath("//input[@id='autocomplete']")). SendKeys("Lenovo");
driver.FindElement(By.XPath("//span[@id='search']/a")).Click();
IList<IWebElement> mobileprice = driver.FindElements(By.XPath("//span[@class='p_price']"));
//I want to store mobiles prices into an array and then print in the console.
int price = mobileprice.Count;
int[] prices = new int[price];
for (int i = 0; i < prices.Length; i++)
{
Console.WriteLine(price);
Console.Read();
}
}
}
}
【问题讨论】:
-
你卡在哪里了?你看到任何错误吗?在哪一行?
-
如果您是 C# 新手,我的一个建议是了解泛型和
List<T>。您可以将此类型视为类似于数组,但它会在您向其中添加元素时调整大小。 -
感谢您的回复。我没有看到任何错误,也无法在控制台中读取价格。
-
我的意图是在数组中获取 mobileprices 并使用 for 循环在控制台中打印价格,但没有显示
-
根据您的代码,您将 mobileprice.Count 存储在一个变量中。然后,您将创建一个您永远不会使用的
prices数组,除非调用prices.Length,它始终是price的值。在你的循环中,你没有访问你的数组。为此,您需要执行prices[i]之类的操作,但这不会有太大帮助,因为您从未真正在数组中放置任何值。