代码之家  ›  专栏  ›  技术社区  ›  Joey Gumbo

重新使用gdi+对象是不是不好的做法?(或者:如何使用多个嵌套的using块而不感到头痛?)

  •  3
  • Joey Gumbo  · 技术社区  · 15 年前

    我目前正在为一个用户控件编写一个相当复杂的画图方法,涉及相当多的绘图代码。我知道所有的gdi+资源都需要适当地处理,所以我将它们包装在 using 块。

    但当我注意到我用了三个 使用 三个不同的街区 SolidBrushes 我想知道我是否不能重复使用它们。创建一个 SolidBrush 用它画画,指定一种不同的颜色,画一些其他的东西,等等。 Dispose() 最后。

    这是明智之举还是我在这里想得太难了?我特别不喜欢太多 使用 块也相互嵌套。虽然好的模式有时会妨碍可读性。

    3 回复  |  直到 12 年前
        1
  •  5
  •   Henk Holterman    15 年前

     using (var a = ...)
     using (var b = ...)
     using (var c = ...)
     {
    
     }
    
        2
  •  1
  •   Jehof    15 年前

    public class MyUserControl : UserControl{
    
      private SolidBrush _brush;
    
      public MyUserControl() {
        _brush = new SolidBrush(Color.Red);
      }
    
      protected override void OnPaint(PaintEventArgs e){
        // Draw with the brush;
      }
    
      protected override void Dispose(bool disposing){
        // other Dispose logic
        if (_brush != null) {
          _brush.Dispose();
        }
      }
    }
    
        3
  •  1
  •   Community CDub    8 年前