1

我从 Andy Wiggly 的帖子中改编了这段代码(他不仅仅是“某个人”——他为 MS Press 共同编写了“MS .NET Compact Framework”):

WebRequest request = HttpWebRequest.Create(uri);
request.Method = Enum.ToObject(typeof(HttpMethods), method).ToString();
request.ContentType = contentType;
((HttpWebRequest)request).Accept = contentType;
((HttpWebRequest)request).KeepAlive = false;
((HttpWebRequest)request).ProtocolVersion = HttpVersion.Version10;

if (method != HttpMethods.GET && method != HttpMethods.DELETE)
{
    Encoding encoding = Encoding.UTF8;
    request.ContentLength = encoding.GetByteCount(data);
    //request.ContentType = contentType; <= redundant; set above
    request.GetRequestStream().Write(
      encoding.GetBytes(data), 0, (int)request.ContentLength);
    request.GetRequestStream().Close();
}

请注意,在第一段代码中,我必须将“请求”转换为 HttpWebRequest;但是,在有条件的情况下,强制转换是不必要的。为什么有区别?“WebRequest”应该改为“HttpWebRequest”吗?如果我这样做,则强制转换为灰色,表明它是不必要的,但 Wiggly 这样做肯定是有原因的,而且仍然:为什么在条件块中消除了强制转换?

4

1 回答 1

3

HttpWebRequest.Create() is kind of a static factory. You cannot override the behaviour in a derived class. Depending on the URI you provide, it can create a HttpWebRequest or a FtpWebRequest. Which are derived from WebRequest. When you know you're creating a Http request, then i suggest you do the following:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri)

or

var request = (HttpWebRequest)WebRequest.Create(uri)

When you want to access the special properties/methods of the derived class which aren't available in the base class, you have to do this cast.

e.g. KeepAlive is not available in the WebRequest base class because it belongs to HttpWebRequest.

Other properties like Method is defined in the base class and therefore you don't need the cast.

于 2014-03-13T18:57:57.053 回答