如何创建接受通用参数的方法?
好的,这就是我正在做的事情:
以下两种方法仅因By.Id
或By.LinkText
private IWebElement FindElementById(string id)
{
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(40));
IWebElement we = null;
wait.Until<bool>(x =>
{
we = x.FindElement(By.Id(id));
bool isFound = false;
try
{
if (we != null)
isFound = true;
}
catch (StaleElementReferenceException)
{
we = x.FindElement(By.Id(id));
}
return isFound;
});
return we;
}
private IWebElement FindElementByLinkText(string id)
{
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(40));
IWebElement we = null;
wait.Until<bool>(x =>
{
we = x.FindElement(By.LinkText(id));
bool isFound = false;
try
{
if (we != null)
isFound = true;
}
catch (StaleElementReferenceException)
{
we = x.FindElement(By.LinkText(id));
}
return isFound;
});
return we;
}
答案 0 :(得分:6)
由于Selenium By
函数是符合Func<string, By>
类型签名的静态成员函数,因此您可以像这样轻松修改代码:
private IWebElement FindElementById(string id)
{
return FindElementBy(By.Id, id);
}
private IWebElement FindElementByLinkText(string linkText)
{
return FindElementBy(By.LinkText, linkText);
}
private IWebElement FindElementBy(Func<string, By> finder, string argument)
{
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(40));
IWebElement we = null;
wait.Until<bool>(x =>
{
we = x.FindElement(finder(argument));
bool isFound = false;
try
{
if (we != null)
isFound = true;
}
catch (StaleElementReferenceException)
{
we = x.FindElement(finder(argument));
}
return isFound;
});
return we;
}