winforms GraphicsPath是否应该在使用后丢弃

lawou6xi  于 7个月前  发布在  其他
关注(0)|答案(2)|浏览(58)

我正在制作一些实用程序类,这些实用程序类可以制作不同类型的符号,以放置在CAD绘图的立面上。我想确保如果我需要释放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);
}
q7solyqu

q7solyqu1#

创建路径的函数应该在后面的using语句中使用

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

如果调用函数CreateCircle而不是getCircle

eni9jsuy

eni9jsuy2#

你不需要在这里把路径作为ref传递。ref只有在你想改变path在调用函数中指向的东西时才有用。删除ref并像往常一样添加using
阅读值类型和引用类型,以及ref实际上有什么用处。

相关问题