简体   繁体   English

静态方法如何返回其自己的抽象类的对象-WebRequest

[英]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.

相关问题 如何在返回抽象类对象的方法中进行服务调用? - How to moq a service call in a method which is returning an object of abstract class? 从抽象类的静态方法返回类引用 - Returning a class reference from the static method of an abstract class 为什么通过其继承的抽象类而不是自己的类来声明对象 - Why declare an object by its inherited abstract class instead of its own class 从其自己的类中声明一个静态对象 - Declaring a static object from inside its own class 如何在自己的类中调用接口方法? - How to call the interface method in its own class? 派生类在自己的静态方法中调用基类的静态方法 - Derived Class Calling static method of base class in its own static method 如何使静态类不断更新自己的变量? - How to make a static class update its own variables constantly? Microsoft 是如何做到的:static class 中的抽象方法? - How did Microsoft do it: Abstract method in static class? 可以抽象基类在C#中访问其自己的抽象属性。 如果是,那么该值将与基础子对象的值相同吗? - can abstract base class access its own abstract property in C#. If yes, then will the value be same as that of underlying child object? 程序类中的抽象方法与静态方法 - Abstract method vs static method in Program class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM