I am making some utility classes that make different types of symbols to place onto an elevation of CAD drawings. I want to make sure that if I need to dispose of the GraphicsPath object that I do so.

In the code below from inside the getCircle function it shows that I am passing the myPath "GraphicsPath" object to the AddStringToPath function.

I cannot use the using(){} scope for this because I am passing the myPath graphics object as a ref.

Is this design ok to use or do I need to go about this a different way to ensure garbage collection?

 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);
        }
有帮助吗?

解决方案

your function which creates the path should be used later in a using statement

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

it would also be better, if you would call the function CreateCircle instead of getCircle

其他提示

You don't need the pass the path as ref here. ref would only be useful if you wanted to change what path points to in the calling function. Get rid of the ref and add using as usual.

And read up on value types and reference types and what ref is actually useful for.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top