2012-12-30 33 views
2

我正在製作一些實用程序類,它們可以將不同類型的符號放置到CAD圖紙的立面上。 我想確保如果我需要處理我這樣做的GraphicsPath對象。如果GraphicsPath在使用後丟棄

在getCircle函數內部的代碼中,它顯示我將myPath「GraphicsPath」對象傳遞給AddStringToPath函數。

我不能使用using(){}作用域,因爲我傳遞了myPath圖形對象作爲參考。

這個設計可以使用嗎?還是我需要去關於這個不同的方式來確保垃圾收集?

GraphicsPath getCircle(Graphics dc, string text = "") 
     { 
      GraphicsPath myPath = new GraphicsPath(); 
      myPath.AddEllipse(symbolCircle); 

      AddStringToPath(dc, ref myPath, text); 

      return myPath; 
     } 
     void AddStringToPath(Graphics dc, ref GraphicsPath path, string text) 
     { 
      SizeF textSize = dc.MeasureString(text, elevFont); 

      var centerX = (path.GetBounds().Width/2) - (textSize.Width/2); 
      var centerY = (path.GetBounds().Height/2) - (textSize.Height/2); 

      // Add the string to the path. 
      path.AddString(text, 
       elevFont.FontFamily, 
       (int)elevFont.Style, 
       elevFont.Size, 
       new PointF(centerX + 2, centerY + 2), 
       StringFormat.GenericDefault); 
     } 

回答

4

您的函數創建的路徑應該在後面using語句

using(var path = getCircle(dc, "Text")) 
{ 
     // do something with path 
} 

使用也將是更好的,如果你想調用函數CreateCircle,而不是getCircle

+0

謝謝。再加上一個更好的命名約定。 –

+0

哪個更好,'var path ='或'GraphicsPath path ='? – barlop

4

您不需要在這裏傳遞路徑refref只有在您想要更改調用函數中的path時纔有用。像往常一樣擺脫ref並添加using

並閱讀價值類型和參考類型以及ref實際上的用途。

+0

+1。請注意,'使用'路徑應該在調用'getCircle'的地方,而不是* insisde *'getCircle',我從閱讀你的問題中感受到。 –

+0

如果您注意到我正在創建getCircle中的路徑並在AddStringToPath中的該路徑上進行操作。我相信我是對的。 –

+0

@Storefront:請按我的建議去做,並閱讀'ref'實際上做了什麼。 'GraphicsPath'是一個引用類型。 –