我从 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 这样做肯定是有原因的,而且仍然:为什么在条件块中消除了强制转换?