我有一个表中的行列表,我想从第一个列表中创建另一个包含某些行的列表。
我的代码是:
public IWebElement InvoiceTable { get { return Driver.FindElement(By.Id("MainContent_gvInvoices")); } }
public IList<IWebElement> InvoiceRows { get { return InvoiceTable.FindElements(By.CssSelector("tbody tr")); } }
public IList<IWebElement> ACInvoiceRows { get; set; }
public void test()
{
foreach(IWebElement row in InvoiceRows)
{
if(row.Text.Contains("AC"))
{
ACInvoiceRows.Add(row);
}
}
Console.WriteLine(ACInvoiceRows.Count);
}
这会引发NullReferenceExcpetion
:
对象引用未设置为对象的实例。
我在这里做错了什么?
答案 0 :(得分:0)
在以下行中,您不会检查row.Text
是否为null
。
if (row.Text.Contains("AC"))
如果row.Text
为null
,您最终会得到NullReferenceException
。这样做是为了检查null
案例。
if (row.Text != null && row.Text.Contains("AC"))
编辑:
ACInvoiceRows
也可能没有设置。如果不是,则在您为其指定实际对象之前无法使用它,例如:
public void test()
{
//Initiate the collection before using it.
ACInvoiceRows = new List<IWebElement>();
foreach(IWebElement row in InvoiceRows)
{
if(row.Text.Contains("AC"))
{
ACInvoiceRows.Add(row);
}
}
Console.WriteLine(ACInvoiceRows.Count);
}
答案 1 :(得分:0)
确保按以下步骤初始化您的驱动程序:
IWebDriver Driver = new ChromeDriver();