【问题标题】:Should the GraphicsPath be disposed after useGraphicsPath 是否应该在使用后被处理掉
【发布时间】:2012-12-15 06:41:37
【问题描述】:

我正在制作一些实用程序类,用于制作不同类型的符号以放置在 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);
        }

【问题讨论】:

    标签: c# winforms memory graphicspath


    【解决方案1】:

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

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

    如果你调用函数CreateCircle而不是getCircle,那就更好了

    【讨论】:

    • 谢谢。加上更好的命名约定。
    • 哪个更好,var path =GraphicsPath path=
    【解决方案2】:

    您不需要在此处将路径传递为refref 仅在您想更改调用函数中 path 指向的内容时才有用。像往常一样删除ref并添加using

    并阅读值类型和引用类型以及 ref 的实际用途。

    【讨论】:

    • +1。请注意,路径的using 应该在调用getCircle 的地方,而不是我从阅读您的问题中感受到的insisde getCircle
    • 如果您注意到我在 getCircle 中创建路径并在 AddStringToPath 中对该路径进行操作。我相信我做对了。
    • @Storefront:请按照我的建议去做,并仔细阅读 ref 的实际作用。 GraphicsPath 是一个引用类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    相关资源
    最近更新 更多