子类怎么访问父类
比如panel创建了一个button对象,单击button,在button的click事件中获得该button的index,然后我想把该index传到父类panel中。请问如何操作?谢谢!
------解决方案--------------------你是说调用父类容器的方法吧?我按你说的做了一个程序,desktop类是继承Form的,icon类继承PictureBox的。然后在desktop上加了两个按钮,addbutton按钮用来创建icon类,Delbutton按钮用来调用删icon,
public partial class desktop : Form
{
private int deleteIndex;
private int counts = 0;
public desktop()
{
InitializeComponent();
}
public void getIndex(int index)
{
deleteIndex = index;
}
//增加按钮
private void addbutton_Click(object sender, EventArgs e)
{
counts++;
int X = 20 + (counts * 32);
int Y = 10 + (counts * 32);
icon iconObject = new icon(this.Controls.Count,this);
iconObject.Location=new Point(X,Y);
this.Controls.Add(iconObject);
}
//删除按钮
private void Delbutton_Click(object sender, EventArgs e)
{
this.Controls.Remove(this.Controls[ "icon " + deleteIndex.ToString()]);
}
}
public class icon : PictureBox
{
private int deleteIndex;
desktop OBJ;
public icon(int index,desktop myParent)
{
OBJ = myParent; //接收父类容器对象
deleteIndex = index;
this.Name = "icon "+index.ToString() ;
this.Size = new Size(32, 32);
this.BackColor = Color.White;
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
//下面调用desktop.getIndex()把该iconObject的index传到desktop中
OBJ.getIndex(deleteIndex);
}
}
icon类的构造函数要定义父类容器的参数,以便在实例化icon时传入desktop类对象