问题
I am trying to get my head around some of my predecessors code who, helpfully, has used 'var' to declare everything.
I have a using statement which is below:
using (var postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
When I put a breakpoint here, postStream shows up in the Autos window as System.Net.ConnectStream. Instead of 'var' I want to use 'ConnectStream' but the compiler doesn't like this.
What am I missing, why can't I write my code like this:
using (ConnectStream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
I know this is trivial but I was always taught not to use 'var' unless you have a specific reason to do so (such as when dealing with LINQ). Am I wrong?
回答1:
ConnectStream
is an internal class, you can't use it explicitly. But it doesn't matter, because you don't need to know that its actual type is ConnectStream
: all you need to know is that it's a Stream
(the return type declared by GetRequestStream
), the actual implementation doesn't really matter.
If you want to specify the type explicitly, just write it like this:
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
(but it has exactly the same meaning as using var
)
回答2:
Theres a great snippet from the var keyword on the InfoQ site. This talks about when and when not to use var. Its not quite as clear cut as don't' use it unless your using linq, its more you use it when you don't need to draw attention to the data type and use typed objects when you need to draw attention to the data type.
Its one of the personal preference things... but normally the best preference is however your boss/code lead/architect likes their code 'grammar' to look to make it uniform.
回答3:
Without knowing this actual API, GetRequestStream()
looks like a factory method, it most likely returns a base-class of ConnectStream.
So you would have to use:
using (ConnectStream postStream = (ConnectStream) request.GetRequestStream()) { ... }
Note that you can simply hover your mouse over postStream
in the editor to see what the compile-time type is.
回答4:
I reused one answer from here: How do I get the filesize from the Microsoft.SharePoint.Client.File object?
It' reply from 'Freejete' and his method 'ReadToEnd' worked like a charm for me.
来源:https://stackoverflow.com/questions/8929733/how-do-i-use-system-net-connectstream