我有必要在運行時動態創建一個頁面的實例(使用硒)。這個想法是從一個字符串中檢索類名並初始化它。如何從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);
但我需要從一個字符串動態地做到這一點。怎麼樣?
請閱讀此處:https://stackoverflow.com/questions/159978/c-sharp-keyword-usage-virtualoverride-vs-new – kiziu