如何使用泛型和工厂设计实例化 PageObject 类

我正在用 c# 开发一个 selenium 框架。页面类使用工厂设计实例化以隐藏实例化逻辑,我希望能够使用 var myPageClass = HelperSelenium.Instance(MyPageClass)而不是实例化类var myPageClass = MyPageClass.Instance(driver)


我已经尝试在 HelperSelenium 类中创建一个泛型函数,但我还不能完全理解泛型是如何工作的。


PageObject 类示例(注意我使用 Instance 方法来实例化该类


public class HomePage : BasePage

{       

    private HomePage(IWebDriver driver, CountryEnum enum) : base(driver) { }


    private static HomePage homePage { get; set; }


    public static HomePage Instance(IWebDriver driver, CountryEnum enum)

    {

        switch (enum)

        {

             case CountryEnum.Sweden:

                 HomePage = new HomePage_SWE(driver);

                 break;

             case CountryEnum.Germany:

                 HomePage = new HomePage_GER(driver);

                 break;

             case CountryEnum.Italy:

                 HomePage = new HomePage_ITA(driver);

                 break;

             default:

                 HomePage = new HomePage_UK(driver);

                 break;

        }


        return homePage;

    }


...

}

public T InstancePage<T>() where T : BasePage

{

    return (T).Instance(WebDriver, CountryEnum.Sweden);

}

Error   CS0119  'T' is a type, which is not valid in the given context  InfrastructureSelenium  C:\testSelenium\Infrastructure\Helper\HelperSelenium.cs 140 Active

Error   CS0119  'T' is a type parameter, which is not valid in the given context    InfrastructureSelenium  C:\testSelenium\Infrastructure\Helper\HelperSelenium.cs 140 Active


慕姐8265434
浏览 100回答 1
1回答

蝴蝶不菲

最后我通过使用修复:&nbsp; &nbsp; &nbsp; &nbsp; public T InstantiatePage<T>() where T : class&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // COUNTRY code as defined in&nbsp; &nbsp; &nbsp; &nbsp; // https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements&nbsp; &nbsp; &nbsp; &nbsp; var className = string.Format("{0}_{1}", typeof(T).FullName, getCulture());&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // T will be base class if no derived class with COUNTRY code suffix is found&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; var classType = Type.GetType(className) ?? typeof(T);&nbsp; &nbsp; &nbsp; &nbsp; // Instantiate the page&nbsp; &nbsp; &nbsp; &nbsp; var instance = Activator.CreateInstance(classType, new object[] { WebDriver });&nbsp; &nbsp; &nbsp; &nbsp; return (T)instance;&nbsp; &nbsp; }我很确定使用 PageObject.PageFactory 可以改善它
打开App,查看更多内容
随时随地看视频慕课网APP