在下面的示例中,返回的pen是否会被销毁(处置)?

' VB'
Public Function GetPen() As System.Drawing.Pen
  Using pen As New System.Drawing.Pen(_Color, _Width)
    pen.DashStyle = _DashStyle
    Return pen
  End Using
End Function

// C#
public System.Drawing.Pen GetPen()
{
    using (System.Drawing.Pen pen = new System.Drawing.Pen(_Color, _Width))
    {
        pen.DashStyle = _DashStyle;
        return pen;
    }
}

[编辑]

只是精度更高... Pen对象是通过引用发送到GetPen的调用者还是像结构一样被“克隆”?我知道,这是一个类,但是对于GDI对象,我不确定...

当外部方法将销毁通过pen获得的GetPen()时,是否会销毁(丢弃)在pen中创建的GetPen()

最佳答案

是的,将丢弃笔。但是,这确实是一个坏主意。您退还已经丢弃的笔!

您要做的是从GetPen中删除Using语句。 Use语句应由GetPen调用方使用:

Using pen As Pen = GetPen()
    ''// Draw with this pen
End Using

或在C#中:
using(Pen pen = GetPen())
{
    // Draw with this pen
}

[编辑]

是的,引用返回到调用方法,而不是副本。这就是为什么如果在GetPen中丢弃笔的原因,则不能在调用方法中使用该笔;-)

由于GetPen和调用方法指向同一个Pen对象,因此只需要在调用方法中调用Dispose。

关于.net - .NET中 'using'的使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2057437/

10-13 06:18