如何使用类属性use扩展方法
本文关键字:扩展 方法 use 属性 何使用 | 更新日期: 2023-09-27 18:25:27
我有一个硒类
public class Driver
{
public IWebDriver Instance { get; set; }
public string baseURL;
public void Initialize()
{
Instance = new FirefoxDriver();
baseURL = "http://localhost:49730/";
Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
}
public void Wait(TimeSpan timespan)
{
Thread.Sleep((int)(timespan.TotalSeconds * 1000));
}
public void Close()
{
Instance.Close();;
}
}
我还创建了一个扩展方法,它是一个显式等待
public static class WebDriverExtensionMethods
public static class WebDriverExtensionMethods
{
public static IWebElement WaitAndFindElement(this Driver driver, By by, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new WebDriverWait(driver.Instance, TimeSpan.FromSeconds(timeoutInSeconds));
return wait.Until(drv => drv.FindElement(by));
}
return driver.Instance.FindElement(by);
}
}
如何调用具有Driver类属性的方法?我想叫司机。Instance.WaitAndFindElement
也许你可以在IWebDriver上写一个扩展,而不是Driver:
public static class WebDriverExtensionMethods
{
public static IWebElement WaitAndFindElement(this IWebDriver driver, By by, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
return wait.Until(drv => drv.FindElement(by));
}
return driver.FindElement(by);
}
}
顺便说一句,这样你只能在驱动程序的Instance属性上调用它。否则,您可以在现有扩展名的基础上添加此扩展名。甚至可能提取通用代码:
public static class WebDriverExtensionMethods
{
private static IWebElement WaitAndFindElementInternal(IWebDriver webDriver, By by, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(timeoutInSeconds));
return wait.Until(drv => drv.FindElement(by));
}
return webDriver.FindElement(by);
}
public static IWebElement WaitAndFindElement(this Driver driver, By by, int timeoutInSeconds)
{
return WaitAndFindElementInternal(driver.Instance, by, timeoutInSeconds);
}
public static IWebElement WaitAndFindElement(this IWebDriver driver, By by, int timeoutInSeconds)
{
return WaitAndFindElementInternal(driver, by, timeoutInSeconds);
}
}
通过这种方式,您可以调用driver.Instance.WaitAndFindElement
和driver.WaitAndFindElement
。