Is there any way to inherit a class without constructors in .NET?

前端 未结 2 1725
名媛妹妹
名媛妹妹 2020-12-31 19:28

I\'m currently trying to modify some HttpWebRequest functions, but I can\'t do it through inheritance because HttpWebRequest has no public constructors (besides the deserial

相关标签:
2条回答
  • 2020-12-31 20:30

    Unless you can trick the serialization constructor to do your bidding, then no, there is no way.

    The constructors of that class are internal, so you have no way of calling them.

    0 讨论(0)
  • 2020-12-31 20:32

    You can't through inheritance from HttpWebRequest (if you don't want to call the serialization constructor) , but you can through composition and delegation, and through inheritance from WebRequest (I'm not sure if that will do it for you, but functionally it is quite similar). WebRequest has a default constructor.

    In this case you then can't have the class 'be' a HttpWebRequest (as in an is-a relationship), since you can't extend from it, but it wil 'be' a WebRequest, which should suffice.

    You could write a class that inherits from WebRequest, that has an instance member of type WebRequest, create a HttpWebRequest and assign to instance member in the constructor of the new type and delegate all calls to that reference (sort of a decorator pattern):

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Text;
    
    namespace ClassLibrary1
    {
        public class MyHttpWebRequest : WebRequest
        {
            private WebRequest request;
    
            public MyHttpWebRequest(string uri)
            {
                request = HttpWebRequest.Create(uri);
            }
    
            public override WebResponse GetResponse()
            {
                // do your extras, or just delegate to get the original code, as long
                // as you still keep to expected behavior etc.
                return request.GetResponse();
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题