这是我想从中返回类对象的通用方法
public class TestBase
{
public T NavigateandReturntheObject<T>() where T : new()
{
//do navigate to page stuff and return the page object
//previously it was - return new T();
//Now i want to do something like this
return PageObjectBase<T>.PageObject;
}
}
调用下面的静态通用类的方法,该类将处理特定类的对象创建
public static class PageObjectBase<T> where T : class, new()
{
private static T singleTonObject;
public static T PageObject
{
get
{
return InstanceCreation();
}
}
public static T InstanceCreation()
{
if (singleTonObject == null)
{
singleTonObject = new T();
}
return singleTonObject;
}
}
如何从我的测试基类中调用PageObject属性,请提出建议。 注意:我搜索了论坛并找到了与泛型方法相关的答案,这是通过反射实现的,我们也可以在自己的案例中使用反射吗?如果是这样,我们该怎么做。
答案 0 :(得分:0)
您可以向NavigateandReturntheObject添加另一个约束“类”
public T NavigateandReturntheObject<T>() where T : class,new()
完整代码。
public class TestBase
{
public T NavigateandReturntheObject<T>() where T : class,new()
{
//do navigate to page stuff and return the page object
//previously it was - return new T();
//Now i want to do something like this
return PageObjectBase<T>.PageObject;
}
}
演示代码
public class TestClass
{
public string Name{get;set;}
public TestClass()
{
Name = "Dummy Name";
}
}
var testBase = new TestBase();
var sample = testBase.NavigateandReturntheObject<TestClass>();
Console.WriteLine(sample.Name);
输出
Dummy Name