SysinfoPanel构造时定义了个面板,可是构造函数中定义了:Panel panel = new Panel();
那么构造结束时 panel 不是就销毁了吗???
一直从事c++,刚看c# 没明白。怎么可以这样?代码如下:class SysinfoPanel:Form
{
readonly float cxCol;
readonly int   cySpace;

public static void Main()
{
Application.Run(new SysinfoPanel());
}
public SysinfoPanel()
{
Text = "Systim information :Panel";
BackColor = SystemColors.ButtonFace;
ForeColor = SystemColors.WindowText;
AutoScroll = true;
        AutoScrollMargin = new Size(10, 10);

Graphics g = CreateGraphics();
SizeF sizef = g.MeasureString(" ",Font);
        cxCol = sizef.Width + SysinfoStrings.MaxLabelWidth(g, Font);
cySpace = Font.Height;

//creat a panel
Panel panel = new Panel();
panel.Parent = this;
panel.Paint += new PaintEventHandler(PanelPaint);
panel.Location = Point.Empty;
        panel.BackColor = Color.Honeydew;
panel.Size = new Size(
             (int)Math.Ceiling(cxCol + SysinfoStrings.MaxValueWidth(g, Font)),
             (int)Math.Ceiling((double)cySpace * SysinfoStrings.Count));
     g.Dispose();
}
void PanelPaint(object obj, PaintEventArgs e)
{
        Graphics g = e.Graphics;
Brush brush = new SolidBrush(ForeColor);
        int iCount = SysinfoStrings.Count;
string[] astrLabels = SysinfoStrings.Labels;
string[] astrValues = SysinfoStrings.Values;
for (int i = 0 ; i< iCount; i++)
{
g.DrawString(astrLabels[i],Font,brush,0,i*cySpace);
g.DrawString(astrValues[i],Font,brush,cxCol,i*cySpace);

}
}
}

解决方案 »

  1.   

    .net是自动垃圾回收机制,会自动完成,不需要干预。不像C++,所以不用担心会出现内存泄露等问题
      

  2.   

    用C#不要用C++的想法,不然你搞不下去!当然精通C++,那是不错的基础
      

  3.   

    或许在设置panel.parent=this的时候 内部实现已经在this里用某种方式引用了这个panel以使this知道panel的存在 
    这样垃圾收集器就会知道panel还有引用 就不会收集他了 猜想而已。。