[英]How is a static method returning a object of its own abstract class - WebRequest
While working on the WebRequest class I noticed that it is an abstract class, and it has a create method which is returning a object of the abstract class. 在处理WebRequest类时,我注意到它是一个抽象类,并且它具有一个create方法,该方法返回该抽象类的对象。
I have read that abstract class cannot be instantiated, so i'm trying to understand how the static method is returning the object 我已经读过抽象类无法实例化,所以我试图了解静态方法如何返回对象
WebRequest req = WebRequest.Create(URl);
Create Method definition: 创建方法定义:
public static WebRequest Create(string requestUriString);
See Documentation 请参阅说明文件
i tried this, and as expected got an error 我尝试了这个,并且按预期得到了一个错误
abstract class Test
{
public static Test Runmachine()
{
return new Test();
}
}
Try this and see for yourself. 试试看,自己看看。 You can return a more specialized, non-abstract version of the same class, eg a class that derives from Test
. 您可以返回同一类的更专业的,非抽象的版本,例如,从Test
派生的类。
abstract class Test
{
public static Test RunMachine()
{
return new SpecializedTest();
}
}
class SpecializedTest : Test {}
I guess what you have missed, is Polymorphism.If you have a base class A and a derived class B, any object of type B, is also of type A. In other words any object of type B can be assigned to a variable of type A. In your case, the return type of the method being WebRequest, doesn't mean that the returned object is a direct instance of WebRequest. 我想您想念的是多态性。如果您有基类A和派生类B,则任何类型B的对象也都是类型A。换句话说,类型B的任何对象都可以分配给变量类型A。在您的情况下,方法的返回类型为WebRequest,并不意味着返回的对象是WebRequest的直接实例。 It can -and since WebRequest is abstract, it has to- be an instance of a derived class. 由于WebRequest是抽象的,因此它可以成为继承类的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.