C# 遍历并更改所有表单对象
我创建了一个带有6张“卡片”的Windows窗体应用程序“卡”是从System.Windows.Forms.PictureBox派生的I类。 我添加了一个名为“id”的成员 有没有一种方法可以遍历“Card”类型的所有对象并更改“id”的值 下面是类定义C# 遍历并更改所有表单对象,c#,winforms,C#,Winforms,我创建了一个带有6张“卡片”的Windows窗体应用程序“卡”是从System.Windows.Forms.PictureBox派生的I类。 我添加了一个名为“id”的成员 有没有一种方法可以遍历“Card”类型的所有对象并更改“id”的值 下面是类定义 public class Card : System.Windows.Forms.PictureBox { System.Drawing.Bitmap Back = MemoryGame.Properties.
public class Card : System.Windows.Forms.PictureBox
{
System.Drawing.Bitmap Back = MemoryGame.Properties.Resources.MG_back;
byte id = 0;
public Card()
{
this.Image = Back;
this.SizeMode = PictureBoxSizeMode.Zoom;
}
public void Flip(System.Drawing.Bitmap bitmap)
{
if (this.Image == Back)
{
this.Image = bitmap;
}
else
{
this.Image = Back;
}
}
public int GetId()
{
return this.id;
}
}
您可以遍历
控件
集合,例如:
int counter = 0;
foreach(var card in this.Controls.OfType<Card>())
{
card.Id = ++counter;
}
int计数器=0;
foreach(此.Controls.OfType()中的var卡)
{
卡片Id=+计数器;
}
您可以遍历控件
集合,例如:
int counter = 0;
foreach(var card in this.Controls.OfType<Card>())
{
card.Id = ++counter;
}
int计数器=0;
foreach(此.Controls.OfType()中的var卡)
{
卡片Id=+计数器;
}
在parentcontrols“Controls”属性上循环。然后您可以检查当前控件是否属于您的类型卡
foreach(var control in parentControl.Controls)
{
if(control is Card c)
{
c.Id = 0 /*Some new value*/
}
}
编辑:本例中使用的类型模式可从parentcontrols“Controls”属性上的C#7.0开始使用。然后您可以检查当前控件是否属于您的类型卡
foreach(var control in parentControl.Controls)
{
if(control is Card c)
{
c.Id = 0 /*Some new value*/
}
}
编辑:本例中使用的类型模式可以从C#7.0开始使用ID是否真的不可访问,或者您就是这样写的?它不可访问,我现在更改了它。我的疏忽,但这并不是阻碍我前进的原因。是我真的无法访问,还是你就这样写在这里?无法访问,我现在更改了它。我的疏忽,但这并不是阻碍我前进的原因。