我正在尝试使用泛型返回一个类的对象。
这是泛型类
public class ClientBase <S>
{
protected S CreateObject()
{
return default(S) ;
}
}这就是我尝试使用它的方式。
public class ClientUser : ClientBase <SomeClass>
{
public void call()
{
var client = this.CreateObject();
client.SomeClassMethod();
}
}虽然我在client对象中获得了SomeClassMethod(),但在运行代码时,它在以下行给出了一个错误:
client.SomeClassMethod();
错误是“对象引用未设置为对象的实例”。我知道泛型类ClientBase的CreateObject()方法中缺少一些东西;只是找不到它。有人能帮我一下吗?
谢谢你的时间..。
发布于 2011-10-02 20:54:12
其中S是引用类型的default(S)为null。在本例中,default(SomeClass)返回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();
}
}发布于 2011-10-02 20:58:48
看看default(T)做了什么:http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx
在本例中,default(S)将返回null (因为它是一个类)-这不是该类的实例。
您需要调用new S()或其他S构造函数,或者在派生类中重写CreateObject。
https://stackoverflow.com/questions/7626436
复制相似问题