C#中的HttpWebRequest的WebRequest VS [英] C# HttpWebRequest vs WebRequest
问题描述
我看到这片code的:
I saw this piece of code:
var request = (HttpWebRequest) WebRequest.Create("http://www.google.com");
为什么需要投(HttpWebRequest的)
?为什么不使用 HttpWebRequest.Create
?又为何 HttpWebRequest.Create
作的WebRequest
,而不是的HttpWebRequest
?
Why do you need to cast (HttpWebRequest)
? Why not just use HttpWebRequest.Create
? And why does HttpWebRequest.Create
make a WebRequest
, not a HttpWebRequest
?
推荐答案
的创建
方法是静态的,只存在于的WebRequest
。调用它作为 HttpWebRequest.Create
可能看起来不同,但实际上它编译成叫 WebRequest.Create
。它只是似乎是的HttpWebRequest
因为继承。
The Create
method is static, and exists only on WebRequest
. Calling it as HttpWebRequest.Create
might look different, but its actually compiled down to calling WebRequest.Create
. It only appears to be on HttpWebRequest
because of inheritance.
的创建
方法在内部,使用工厂模式做实际创建对象的基础上,乌里
你传递给它。实际上,你可以找回其他的对象,如的FtpWebRequest
或 FileWebRequest
,这取决于乌里
。
The Create
method internally, uses the factory pattern to do the actual creation of objects, based on the Uri
you pass in to it. You could actually get back other objects, like a FtpWebRequest
or FileWebRequest
, depending on the Uri
.
这篇关于C#中的HttpWebRequest的WebRequest VS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!