将许多不同的类传递给一个方法C#
你好,我有如下方法:将许多不同的类传递给一个方法C#,c#,C#,你好,我有如下方法: public EventItemPage LaunchItemsActionByRowIndex(int RowIndex) { // does some other stuff var eventItemPage = new EventItemPage(driver); eventItemPage.WaitForPageToLoad(); return eventItemPage;
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;
}
我想将这两个方法结合起来,将类作为参数传入,并将它们移动到一个新类,该类将由上面列出的类继承。我需要访问类上的一些方法,还需要确保调用了构造函数。我曾尝试使用如下所示的create instance activator,但认为我没有正确使用它
object obj = (yourPage)Activator.CreateInstance(typeof(StringBuilder), yourPage);
我一直在研究,但我很困惑,如果这是可能的或没有。我没有在上面提到,我们将selenium驱动程序的实例传递给我们将要使用的类的构造函数。按照您的要求去做并非不可能,但您需要稍微修改类的工作方式 不能对类强制使用带参数的构造函数,但可以强制使用无参数构造函数:
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;
}
附录 还有其他方法可以做到这一点 您可以使用继承而不是接口。这允许您对共享逻辑使用单个实现(例如,如果
WaitForPageToLoad()
对两个类执行完全相同的操作)。但是,除非我弄错了,否则您将失去我在示例中使用的干净无参数构造函数。“这将由上面列出的类继承”--您没有在任何地方列出任何类。也许用您作为成员所需的对象类型编写一个小类是一种解决方案?然后,您可以将包含两个所需对象的类实例作为参数发送到函数/方法。您可以定义
泛型方法
,并注入所需的对象
,而不是使用激活器
创建它。您还可以使用两个对象实现为方法返回的“对象”的接口。使用WaitForPageToLoad方法创建一个基类,并从中继承StandardSalesforcePage和EventItemPage,然后重写该方法。更改LaunchViewActionMethod以返回基类object谢谢,我将对此进行详细说明try@NicolePhillips乐意帮忙:)
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
}