How do I create a method that accepts generic parameters?
如何创建接受通用参数的方法?
Ok, here's the exact thing I'm working on:
好的,这是我正在做的事情:
The 2 methods below differ only by By.Id
or By.LinkText
下面的两种方法仅有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;
}
1 个解决方案
#1
Since the Selenium By
functions are static member functions conforming to the type signature of a Func<string, By>
, you could easily modify your code like this:
由于Selenium By函数是符合Func
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;
}
#1
Since the Selenium By
functions are static member functions conforming to the type signature of a Func<string, By>
, you could easily modify your code like this:
由于Selenium By函数是符合Func
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;
}