泛型和返回类对象
我正在尝试使用泛型返回一个类的对象。
这是通用类,
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.一些类方法();
错误是“对象引用未设置到对象的实例”。我知道通用类 ClientBase 的 CreateObject() 方法中缺少一些内容;只是想不通这一点。有人可以帮我吗?
感谢您抽出时间...
I am trying to return an object of a class using the generics.
This is the generic class
public class ClientBase <S>
{
protected S CreateObject()
{
return default(S) ;
}
}
This is how I am trying to use it...
public class ClientUser : ClientBase <SomeClass>
{
public void call()
{
var client = this.CreateObject();
client.SomeClassMethod();
}
}
While I get the SomeClassMethod()
in the client object, when running the code it gives an error at the line:
client.SomeClassMethod();
Error is 'Object reference not set to an instance of an object'. I know there is something missing in the generic class ClientBase's CreateObject() method; just cant figure that bit out. Could someone help me here please?
Thanks for your time...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
default(S)
其中S
是引用类型,为 null。在您的情况下,default(SomeClass)
返回 null。当您尝试对空引用调用方法时,就会出现异常。您是否试图返回
SomeClass
的默认实例?您可能想在泛型类中使用new()
约束并返回 new S(),如下所示:如果
S
需要作为引用类型,您也可以将其限制为class
:default(S)
whereS
is a reference type is null. In your case,default(SomeClass)
returns null. When you try to invoke a method on a null reference, that's when you get your exception.Are you trying to return a default instance of
SomeClass
? You may want to use anew()
constraint andreturn new S()
in your generic class instead, like so:If
S
needs to be a reference type you can also constrain it toclass
:查看
default(T)
的作用:http:// msdn.microsoft.com/en-us/library/xwth0h0d.aspx在您的情况下,
default(S)
将返回 null (因为它是一个类) - 这不是一个实例班级的。您需要调用
new S()
或其他一些S
构造函数,或者在派生类中重写CreateObject
。See what
default(T)
does: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspxIn your case,
default(S)
is going to return null (because it's a class) - this is not an instance of the class.You either need to call
new S()
or some otherS
constructor or overrideCreateObject
in your derived class.