如何从另一个泛型方法调用泛型 属性

How to call generic property from another generic method

这是我的通用方法,我想从中 return class 对象

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

上面的方法调用下面的静态泛型 class,它将处理特定 class

的对象创建
 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;
    }

}

如何从我的测试库class调用PageObject属性请指教。 注意:我搜索了论坛并找到了与通用方法相关的答案到另一个通用方法 calling.The 同样是通过 reflection.Can 实现的 我们在我的案例中也使用反射吗?如果可以,我们该怎么做。

您可以添加另一个约束 'class' 到 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