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

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

For example:

BitmapImage bitmap = new BitmapImage();

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


        
5条回答
  •  孤街浪徒
    2020-12-03 10:05

    Its important to point out that using is actually compiled into various lines of code, similar to lock, etc.

    From the C# language specification.... A using statement of the form

    using (ResourceType resource = expression) statement
    

    corresponds to one of two possible expansions. When ResourceType is a value type, the expansion is

    {
        ResourceType resource = expression;
        try {
            statement;
        }
        finally {
            ((IDisposable)resource).Dispose();
        }
    }
    

    Otherwise, when ResourceType is a reference type, the expansion is

    {
        ResourceType resource = expression;
        try {
            statement;
        }
        finally {
            if (resource != null) ((IDisposable)resource).Dispose();
        }
    }
    

    (end language specification snippet)

    Basically, at compile time its converted into that code. There is no method called using, etc. I tried to find similar stuff in the vb.net language specification but I couldn't find anything, presumably it does the exact same thing.

提交回复
热议问题