2017-05-05 65 views
0

你好,我有一个像下面的方法:传递许多不同类型的一种方法C#

public EventItemPage LaunchItemsActionByRowIndex(int RowIndex) 
    { 
     // does some other stuff 

     var eventItemPage = new EventItemPage(driver); 
     eventItemPage.WaitForPageToLoad(); 

     return eventItemPage; 
    } 

    public StandardSalesforcePage LaunchViewActionByRowIndex(int RowIndex, string actionItem) 
    { 
     // Does the same as above method 

     var bookDetailPage = new StandardSalesforcePage(driver); 
     bookDetailPage.WaitForPageToLoad(); 

     return bookDetailPage; 
    } 

我想这两种方法将它们合并,并在传递类作为参数,并移动到一个新的类,将被上面列出的类继承。我需要访问类的一些方法,并且还要确保构造函数被调用。我试图使用下面的创建实例激活器,但不认为我正确使用它。

object obj = (yourPage)Activator.CreateInstance(typeof(StringBuilder), yourPage); 

我一直在研究很多,但是如果可能或者不可能,我很困惑。上面我没有提到,我们将一个selenium驱动实例传递给我们将要使用的类的构造函数。

+2

“将被上面列出的类继承” - 您没有在任何地方列出任何类。 –

+2

也许这是一个解决方案,用你需要的对象类型作为成员编写一个小类。然后你可以用你需要的对象作为参数发送你的类的一个实例给你的函数/方法 –

+0

你可以定义一个“通用方法”并注入所需的对象而不是用Activator创建它。 https://msdn.microsoft.com/en-us/library/twcad0zb.aspx – zanseb

回答

1

做你所要求的事情并不是不可能的,但你需要稍微修改你的课程的工作方式。

您不能强制对一类参数的构造函数,但你可以强制执行,它有一个构造:

public T LaunchFooByRowIndex<T>(int RowIndex, string actionItem = String.Empty) where T : IFoo, new() 
{ 
    // does some other stuff 

    T myObject = new T(); 
    myObject.LoadDriver(driver); 
    myObject.WaitForPageToLoad(); 

    return myObject; 
} 

注意,我做了可选的第二个参数,以便这两个方法签名兼容。

通过提及new(),确保您只能使用具有无参数构造函数的类(并且还实现IFoo)。处理泛型类型时,可以调用无参数构造函数(假设您需要它的存在)。

但是,你需要设置你的类如下:

public interface IFoo 
{ 
    void LoadDriver(Driver driver); 
    void WaitForPageToLoad(); 
} 

public class MyFooClass : IFoo 
{ 
    //parameterless constructor exists implicitly, 
    //UNLESS you have defined constructors with parameters. 
    //In that case, you need to explicitly make a parameterless constructor. 

    //and then you implement your interface methods here 
} 

附录

还有其他的方法来做到这一点。

您可以使用继承而不是接口。这允许您为共享逻辑实现单个实现(例如,如果WaitForPageToLoad()对您的两个类完全相同)。
但是,除非我错了,那么你就像我在我的例子中使用的干净的无参数构造函数失去了。

+0

谢谢我将试试这个 –

+0

你是摇滚明星,谢谢你的工作很棒。 –

+0

@NicolePhillips高兴地帮助:) – Flater

相关问题