从c#转换到VB.NET时不工作

  • 本文关键字:工作 NET VB 转换 c# vb.net
  • 更新时间 :
  • 英文 :


我可能有点傻。我正在做一个转换从c#到VB。.NET的一小段代码下载视频,虽然这在c#中工作得很好,但在VB.NET中却不行。代码如下:

using (var input = await client.GetStreamAsync(video.Uri))
{
byte[] buffer = new byte[16 * 1024];
int read;
int totalRead = 0;
Console.WriteLine("Download Started");
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
totalRead += read;
Console.Write($"rDownloading {totalRead}/{totalByte} ...");
}
Console.WriteLine("Download Complete");
}

在c#中,这可以下载一个视频,但是在VB中。. NET, 'while'行语法不能正确转换,因此没有任何下载。有人能帮助VB吗?. NET语法的'while'行请?否则,'read'似乎永远不会大于零。

VB。. NET代码目前看起来像这样:

Using input = Await client.GetStreamAsync(video.Uri)
Dim buffer = New Byte(16 * 1024) {} '(81919) {} ' (16 * 1024) {}
Dim read As Integer
Dim totalRead = 0
Console.Write("Download Started")
While read = (input.Read(buffer, 0, buffer.Length) > 0)
output.Write(buffer, 0, read)
totalRead += read
Console.Write($"Downloading {totalRead}/{totalByte} ...")
End While
Console.Write("Download Complete")
End Using

VB对赋值和相等性测试使用相同的操作符,因此表达式中任何尝试的赋值都将被解释为相等性测试。解决方案是提取赋值并在循环之前和循环结束时重新生成它:

read = input.Read(buffer, 0, buffer.Length)
Do While read > 0
output.Write(buffer, 0, read)
totalRead += read
Console.Write($"Downloading {totalRead}/{totalByte} ...")
read = input.Read(buffer, 0, buffer.Length)
Loop

VB可以增强为一个单独的操作符来允许表达式内的赋值(参见Python的'walrus'操作符),但不再计划对语言进行更改。

平心而论,我从来不喜欢c#允许赋值作为表达式。

然而,我也不喜欢重复那个read语句!!

那么,if块的代价,我们得到:

Using input As Stream = Await client.GetStreamAsync(video.Url)
Dim buffer(16 * 1024) As Byte
Dim read As Integer
Dim totalRead As Integer = 0
Console.WriteLine("Download Started")
Do
read = input.Read(buffer, 0, buffer.Length)
If read > 0 Then
output.Write(buffer, 0, read)
totalRead += read
Console.Write($"{vbCrLf}Dwnloading {totalRead}/{totalByte} ....")
End If
Loop While read > 0
Console.WriteLine("Download Complete")

End Using

相关内容

  • 没有找到相关文章

最新更新