简体   繁体   中英

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.

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)?

Just remove the Key word

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; 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)
  2. Using Statement (Visual Basic)
  3. With...End With Statement (Visual Basic)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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