如何使用 System.Net.ConnectStream?
我正在尝试了解我前辈的一些代码,他们使用“var”来声明所有内容,这很有帮助。
我有一个 using 语句,如下所示:
using (var postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
当我在此处放置断点时,postStream 在“自动”窗口中显示为 System.Net.ConnectStream。我想使用“ConnectStream”而不是“var”,但编译器不喜欢这样。
我错过了什么,为什么我不能像这样编写我的代码:
using (ConnectStream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
我知道这是微不足道的,但我总是被教导不要使用“var”,除非你有特定的原因这样做(例如在处理 LINQ 时)。我错了吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ConnectStream
是一个内部类,您不能显式使用它。但这并不重要,因为您不需要知道它的实际类型是 ConnectStream:您需要知道的是它是一个 Stream(返回类型)由GetRequestStream
声明),实际实现并不重要。如果你想显式指定类型,就这样写:(
但和使用
var
的含义完全相同)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 isConnectStream
: all you need to know is that it's aStream
(the return type declared byGetRequestStream
), the actual implementation doesn't really matter.If you want to specify the type explicitly, just write it like this:
(but it has exactly the same meaning as using
var
)InfoQ 网站上有一段来自 var 关键字的精彩片段。这里讲的是什么时候使用var,什么时候不使用var。它不像不使用它那么明确,除非您使用 linq,当您不需要引起对数据类型的注意时,您更多地使用它,而当您需要引起对数据类型的注意时,则使用类型化对象。
这是个人偏好的事情之一......但通常最好的偏好是您的老板/代码主管/架构师喜欢他们的代码“语法”以使其统一。
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.
我重复使用了这里的一个答案:
如何获取文件大小来自 Microsoft.SharePoint.Client.File 对象?
它来自“Freejete”的回复和他的方法“ReadToEnd”对我来说就像一个魅力。
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.