繁体   English   中英

方法的通用类型参数

[英]Generic type parameter for a method

如何创建接受通用参数的方法?

好的,这是我正在研究的确切内容:

下面的2种方法仅By.IdBy.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;
    }

由于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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM