简体   繁体   English

C#与VB.NET中的等效使用

[英]C# Using With Equivalent in VB.NET

var baseAddress = new Uri("http://www.aaa.com");
    var cookieContainer = new CookieContainer();
    using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
    using (var client = new HttpClient(handler){ BaseAddress = baseAddress })
{}

I tried to convert this code with the Developer Fusion tool to VB.NET but was not successful. 我尝试使用Developer Fusion工具将此代码转换为VB.NET,但未成功。

Dim baseAddress = New Uri("http://www.aaa.com")
Dim cookieContainer = New CookieContainer()
Using handler = New HttpClientHandler() With { _
    Key .CookieContainer = cookieContainer _
}
    Using client = New HttpClient(handler) With { _
        Key .BaseAddress = baseAddress _
    }
    End Using
End Using

an error occured "key . " 错误发生了“键”。

What is the VB.NET equivalent of this code (using with statement)? VB.NET的等效代码是什么( with语句一起使用)?

Just remove the Key word 只需删除Key

Using handler = New HttpClientHandler() With { _
    .CookieContainer = cookieContainer _
}
    Using client = New HttpClient(handler) With { _
        .BaseAddress = baseAddress _
    }
    End Using
End Using

I learnt something new ( Object Initializers: Named and Anonymous Types ) from Kilanny's answer; 我从Kilanny的答案中学到了新的东西( 对象初始化器:命名和匿名类型 )。 here's how I refactored the converted code: 这是我重构转换后的代码的方式:

    Dim baseAddress = New Uri("http://www.aaa.com")
    Dim cookieContainer = New Net.CookieContainer()
    Using handler As New HttpClientHandler
        With handler
            .CookieContainer = cookieContainer
            Using client As New HttpClient(handler)
                With client
                    .BaseAddress = baseAddress
                End With
            End Using
        End With
    End Using
  1. Object Initializers: Named and Anonymous Types (Visual Basic) 对象初始化程序:命名和匿名类型(Visual Basic)
  2. Using Statement (Visual Basic) 使用语句(Visual Basic)
  3. With...End With Statement (Visual Basic) With ... End With语句(Visual Basic)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM