如何在C#中从字符串初始化继承的类?

时间:2017-06-26 13:00:02

标签: c# selenium

我有必要在运行时动态创建页面实例(使用selenium)。我们的想法是从字符串中检索类名并初始化它。

假设我有一个“GenericPage”:

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

第二个类继承自GenericPage,实现了Proceed

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);

但我需要从字符串中动态执行此操作。怎么样?

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

虽然使用“新”方法隐藏基类中具有相同名称的方法总是很棘手,但您可以通过调用以下方法来解决问题:

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