2017-06-26 61 views
1

我有必要在運行時動態創建一個頁面的實例(使用硒)。這個想法是從一個字符串中檢索類名並初始化它。如何從C#中的字符串初始化一個繼承的類?

比方說,我有一個「GenericPage」:

public class GenericPage 
    { 
     public void Proceed(string testName) 
     { 
     //Basic implementation 
     } 
    } 

從GenericPage第二類繼承的實現繼續

public class WhatIsYourNamePage : GenericPage 
{ 
    [FindsBy(How = How.Id, Using = "fieldName")] 
    [CacheLookup] 
    private IWebElement UserName { get; set; } 

    [FindsBy(How = How.Id, Using = "fieldSurname")] 
    [CacheLookup] 
    private IWebElement UserSurname { get; set; } 

    [FindsBy(How = How.Id, Using = "submit-first-inner-1")] 
    [CacheLookup] 
    private IWebElement Submit { get; set; } 

    new public void Proceed(string testName) 
    { 
     var userData = ExcelDataAccess.GetTestData(testName); 
     UserName.EnterText(userData.fieldName, Costants.UserNameElementName); 
     UserSurname.EnterText(userData.fieldSurname, Costants.SurnameElementName); 
     Thread.Sleep(5000); 
     Submit.ClickOnIt(Costants.SubmitButtonElementName); 
     Thread.Sleep(5000); 
    } 
} 

所以這裏就是我試圖動態創建WhatIsYourNamePage:

var type = Type.GetType("WhatIsYourNamePage"); 
var myObject = (GenericPage)Activator.CreateInstance(type); 
myObject.Proceed("LogInTest"); 

問題是這樣調用GenericPage.Proceed,但我想WhatIsYourNamePage.Proceed。

當然我可以改變:

var myObject = (WhatIsYourNamePage)Activator.CreateInstance(type); 

但我需要從一個字符串動態地做到這一點。怎麼樣?

+0

請閱讀此處:https://stackoverflow.com/questions/159978/c-sharp-keyword-usage-virtualoverride-vs-new – kiziu

回答

1

假設您應該聲明Proceed方法爲虛擬。不要使用new關鍵字來覆蓋繼承類中的方法(除非你真的知道你在做什麼,因爲它不覆蓋方法(OOP多態),但隱藏它)。所以只是override它與關鍵字覆蓋。如果你這樣做 - myObject.Proceed("LogInTest");將在繼承的類中調用,而不需要進一步修改代碼。

事情是這樣的:

public class GenericPage 
{ 
    public virtual void Proceed(string testName) 
    { 
    //Basic implementation 
    } 
} 

public class WhatIsYourNamePage : GenericPage 
{ 
    [FindsBy(How = How.Id, Using = "fieldName")] 
    [CacheLookup] 
    private IWebElement UserName { get; set; } 

    [FindsBy(How = How.Id, Using = "fieldSurname")] 
    [CacheLookup] 
    private IWebElement UserSurname { get; set; } 

    [FindsBy(How = How.Id, Using = "submit-first-inner-1")] 
    [CacheLookup] 
    private IWebElement Submit { get; set; } 

    public override void Proceed(string testName) 
    { 
     var userData = ExcelDataAccess.GetTestData(testName); 
     UserName.EnterText(userData.fieldName, Costants.UserNameElementName); 
     UserSurname.EnterText(userData.fieldSurname, Costants.SurnameElementName); 
     Thread.Sleep(5000); 
     Submit.ClickOnIt(Costants.SubmitButtonElementName); 
     Thread.Sleep(5000); 
    } 
} 
0

雖然與「新」的方法隱藏具有相同名稱的方法從基類的工作始終是棘手的,你可以通過調用這樣的方法解決問題:

type.GetMethod("Proceed").Invoke(myObject, new[] { "LogInTest" });