哪种方式更可取?
A:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
B:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.GetRequestStream().Write(data, 0, data.Length);
选择C:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
}
但是是的,我会关闭请求流。可能不是绝对需要的,但我不想假设——特别是,除非你有充分的理由相信不是需要的(例如文档),否则实现可能会随着时间的推移而改变,并在以后破坏"懒惰"代码。
如果你发现自己经常这样做,你可以总是写一个实用方法(甚至可能是一个扩展方法):
public static void WriteRequestData(this WebRequest request, byte[] data)
{
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
}
}
那就称之为:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.WriteRequestData(data);
我参加聚会有点晚了,但这个问题仍然很重要。我想补充一点:MSDN示例还演示/建议在编写完成后关闭流。
Stream newStream = myHttpWebRequest.GetRequestStream ();
newStream.Write (byte1, 0, byte1.Length);
Console.WriteLine ("The value of 'ContentLength' property after sending the data is {0}", myHttpWebRequest.ContentLength);
// Close the Stream object.
newStream.Close ();
我喜欢@Jon的例子,并遵循类似的模式。