【问题标题】:Visual Basic while loop syntaxVisual Basic while 循环语法
【发布时间】:2018-07-12 13:56:36
【问题描述】:

我在下面的代码中挣扎:

    Dim req = WebRequest.Create(Uri)
    Dim resp = req.GetResponse()
    Dim stream As Stream = resp.GetResponseStream()

    Dim Buffer As Byte() = New Byte(1023) {}
    Dim MemStream As New MemoryStream()
    Dim BytesRead As Integer = 0
    Dim totalBytesRead As Long = 0

    Dim reader As New BinaryReader(stream)

    While ((BytesRead = reader.Read(Buffer, 0, Buffer.Length)) > 0)
        BytesRead = reader.Read(Buffer, 0, Buffer.Length)
        MemStream.Write(Buffer, 0, BytesRead)
        totalBytesRead += BytesRead
    End While

尽管阅读器中有数据,但从未进入 while 循环。从未设置变量 BytesRead,这让我认为它将“BytesRead = reader.Read(...)”视为相等验证器。但是没有运气,因为我在调试模式下尝试将 BytesRead 变量更改为 1024(缓冲区的长度(最大读取值)),但结果相同。

我解决了这个问题,将 while 循环更改为以下“do-while”循环:

    Do
        BytesRead = reader.Read(Buffer, 0, Buffer.Length)
        MemStream.Write(Buffer, 0, BytesRead)
        totalBytesRead += BytesRead
    Loop While BytesRead > 0

我的问题是;为什么 while 循环没有按我的预期工作?:

((BytesRead = reader.Read(Buffer, 0, Buffer.Length)) > 0) => ((output) > 0)

【问题讨论】:

    标签: .net vb.net


    【解决方案1】:

    将 Option Strict 设置为 On,您将看到发生了什么。在 VB 中,= 运算符既是赋值运算符又是比较运算符。当使用一段时间时,它将比较两个值并返回真或假。然后它会尝试对布尔值(不是值)执行 > 0。

    总之

    While ((BytesRead = reader.Read(Buffer, 0, Buffer.Length)) > 0)
    

    会做:BytesRead 是否等于 reader.Read(Buffer, 0, Buffer.Length) ?这个布尔值是否大于 0。

    我认为这段代码可以在 C# 中运行,因为它有 = 和 ==。

    【讨论】:

    • 我试试看。
    • @MortenKristensen 我建议你立即为整个项目设置 Option Strict On :)
    • 是的,我已经为我所有的最新项目都这样做了,但是我目前正在使用的这个项目已经相当老了,而且该选项从未启用,因此很遗憾启用它非常困难。
    • 但是非常好的答案,这就是我所期望的,但是,您能解释一下以下内容吗?我试图在调试时手动更改值:BytesRead = 1024。这是怎么回事:while((1024 = 1024) > 0) 没有进入循环,因为它本质上变成了 while([true==1] > 0)?
    • @MortenKristensen 查看one of my question 了解 True = -1 的原因
    猜你喜欢
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2014-10-14
    • 1970-01-01
    相关资源
    最近更新 更多