为什么我的WebRequest / HttpWebRequest对象有时需要强制转换,有时则不需要?

时间:2014-03-13 18:52:07

标签: c# casting httpwebrequest webrequest compact-framework2.0

我在Andy Wiggly的帖子中修改了这段代码(不仅仅是#34;有些人&#34; - 他共同编写了#34; MS .NET Compact Framework&#34;用于MS Press):< / p>

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();
}

请注意我在第一个代码块中如何投射&#34; request&#34;作为HttpWebRequest;但是,在有条件的情况下,铸造是不必要的。为什么不同?应该&#34; WebRequest&#34;是&#34; HttpWebRequest&#34;代替?如果我这样做,那么投射是灰色的,表明它是不必要的,但是Wiggly必须这样做是有原因的,并且仍然是:为什么在条件块内避免了投射?

1 个答案:

答案 0 :(得分:3)

HttpWebRequest.Create()是一种静态工厂。您无法覆盖派生类中的行为。根据您提供的URI,它可以创建HttpWebRequest或FtpWebRequest。哪些是从WebRequest派生的。当您知道自己正在创建Http请求时,我建议您执行以下操作:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri)

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

如果要访问基类中不可用的派生类的特殊属性/方法,则必须执行此转换。

e.g。 KeepAlive在WebRequest基类中不可用,因为它属于HttpWebRequest。

其他属性如Method在基类中定义,因此您不需要演员。

相关问题