C# 如何创建自定义类的枚举?

C# 如何创建自定义类的枚举?,c#,enums,C#,Enums,我的表单上有4组控件,我希望将每个控件组绑定到自己的类中,然后能够枚举这些组,比如 class Group1 { public static Label label = form.Lbl1; public static Panel panel = form.pnl1; } class Group2 { public static Label label = form.lbl2; public static Panel panel = form.pnl2; }

我的表单上有4组控件,我希望将每个控件组绑定到自己的类中,然后能够枚举这些组,比如

class Group1
{
    public static Label label = form.Lbl1;
    public static Panel panel = form.pnl1;
}

class Group2
{ 
    public static Label label = form.lbl2;
    public static Panel panel = form.pnl2;
}
lbl1.Visible = true;
lbl2.Visible = true;
等通过第4组。。。然后

enum Groups
{
    Group1,
    Group2,
    Group3,
    Group4
}
这样就不用写这样的东西了

class Group1
{
    public static Label label = form.Lbl1;
    public static Panel panel = form.pnl1;
}

class Group2
{ 
    public static Label label = form.lbl2;
    public static Panel panel = form.pnl2;
}
lbl1.Visible = true;
lbl2.Visible = true;
等等。。。我可以写

foreach (Group group in Groups) 
{
    group.label.visible = true;
}
就这样吧。我知道我可以创建一个组类,然后实例化四个实例并进行赋值,将它们添加到一个列表中,然后在列表上执行foreach,但是有没有一种方法可以在不实例化内容的情况下实现这一点

==更新== 我已经找到了一些我想要的工作方式,但我不知道这是否是一个好的做法。我相信我的新手编码技能将在这里大放异彩

在我的Form.Designer.cs上,我将面板上的修改器从

private System.Windows.Forms.Panel myPanel1;
private System.Windows.Forms.Panel myPanel2;

然后在我的Form.cs文件中添加了类和子类

class ControlGroups 
{
    public static class Group1
    {
        public static Panel panel = Form.myPanel1;
    }

    public static class Group2
    {
        public static Panel panel = Form.myPanel2;
    }
}
稍后在我的代码中,我可以

ControlGroups.Group1.panel.Visible = true;
ControlGroups.Group2.panel.Visible = true;
一切都很好

有没有一种方法可以让我对控制组进行foreach?比如

foreach (Class group in ControlGroups.Subclasses) {
    group.panel.Visible = true;
}

谢谢。

如果您的所有组都包含相同的组件,请创建一个通用占位符

class Group
{
    public Label Label { get; set; }
    public Panel Panel { get; set; }
}
然后


Enum不是用于此目的的方便工具。您正在寻找类似对象的集合(基本相同或至少具有相同的基础)。

您可以使用数组/列表:

创建一个类:

class GroupClass
{
      public Label labelValue { get; set;}
      public Panel panelValue { get; set;}
}
创建类的对象以存储值:

GroupClass first_group = new GroupClass();
first_group.labelValue = form.Lbl1;
first_group.panelValue = form.pnl1;

GroupClass second_group = new GroupClass();
second_group.labelValue = form.Lbl2;
second_group.panelValue = form.pnl2;
将这些组对象添加到列表:

List<GroupClass> listOfGroups = new List<GroupClass>();
listOfGroups.Add(first_group);
listOfGroups.Add(second_group);

如果您的主要目标是实现foreach(分组中的分组)为什么要使用enum?将类对象存储在一个数组中并访问每个对象。感谢LNS的回复LNS。我知道我可以这样做,但在我的最后一段中,我问是否有一种不创建类实例的方法。我知道enum不合适,但我喜欢enum的特点是它们不需要实例化。我用一个更好的例子更新了我的问题,说明了我正在尝试做什么。我将感谢你的意见@user2320861 Hm,问题是您可以实现它,但是在本例中,foreach循环需要您迭代对象引用。使用您可以思考的反射进行迭代:感谢您的输入。我签出了那个链接,我认为它很接近,但我不知道如何访问foreach循环中的成员,因为foreach变量在运行时是“类型化”的。无论如何,我认为列表方法是目前阻力最小的方法。
List<GroupClass> listOfGroups = new List<GroupClass>();
listOfGroups.Add(first_group);
listOfGroups.Add(second_group);
foreach (GroupClass groupObj in listOfGroups ) 
{
    groupObj.labelValue.visible = true;
}