我正在尝试使用泛型返回类的对象。

这是通用类

public class ClientBase <S>
{
    protected S CreateObject()
    {
        return default(S)  ;
    }
}


这就是我试图使用它的方式...

public class ClientUser : ClientBase <SomeClass>
{

    public void call()
    {
        var client = this.CreateObject();
        client.SomeClassMethod();
     }
}


当我在客户端对象中获得SomeClassMethod()时,在运行代码时,它在一行上给出了错误:

client.SomeClassMethod();

错误是“对象引用未设置为对象的实例”。我知道通用类ClientBase的CreateObject()方法中缺少一些内容;只是想不出来那一点。有人可以帮我吗?

谢谢你的时间...

最佳答案

default(S)其中S是引用类型为null。在您的情况下,default(SomeClass)返回null。当您尝试在null引用上调用方法时,即得到异常。

您是否要返回SomeClass的默认实例?您可能想在类中使用new()约束和return new S(),如下所示:

public class ClientBase<S> where S : new()
{
    protected S CreateObject()
    {
        return new S();
    }
}


如果S需要作为引用类型,您也可以将其限制为class

public class ClientBase<S> where S : class, new()
{
    protected S CreateObject()
    {
        return new S();
    }
}

09-05 21:41
查看更多