How does the “Using” statement translate from C# to VB?

前端 未结 5 949
星月不相逢
星月不相逢 2020-12-03 09:20

For example:

BitmapImage bitmap = new BitmapImage();

byte[] buffer = GetHugeByteArray(); // from some external source
using (MemoryStream stream = new Memor         


        
5条回答
  •  -上瘾入骨i
    2020-12-03 10:15

    Using has virtually the same syntax in VB as C#, assuming you're using .NET 2.0 or later (which implies the VB.NET v8 compiler or later). Basically, just remove the braces and add a "End Using"

    Dim bitmap as New BitmapImage()
    Dim buffer As Byte() = GetHugeByteArrayFromExternalSource()
    Using stream As New MemoryStream(buffer, false)
        bitmap.BeginInit()
        bitmap.CacheOption = BitmapCacheOption.OnLoad
        bitmap.StreamSource = stream
        bitmap.EndInit()
        bitmap.Freeze()
    End Using
    

    You can get the full documentation here

    • http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx

    EDIT

    If you're using VS2003 or earlier you'll need the below code. The using statement was not introduced until VS 2005, .NET 2.0 (reference). Thanks Chris!. The following is equivalent to the using statement.

    Dim bitmap as New BitmapImage()
    Dim buffer As Byte() = GetHugeByteArrayFromExternalSource()
    Dim stream As New MemoryStream(buffer, false)
    Try
        bitmap.BeginInit()
        bitmap.CacheOption = BitmapCacheOption.OnLoad
        bitmap.StreamSource = stream
        bitmap.EndInit()
        bitmap.Freeze()
    Finally
        DirectCast(stream, IDisposable).Dispose()
    End Try
    

提交回复
热议问题