简体   繁体   English

使用变量引用对象(C#)

[英]Referencing objects using a variable (c#)

I've been doing a program which needs to change object attributes during the execution. 我一直在做一个程序,在执行过程中需要更改对象属性。 In order for me to have a easy management I've kept the original object name ie "button1" 为了便于管理,我保留了原始对象名称,即“ button1”

My question is if there is a way to reference object names by variables to be changed with a loop 我的问题是是否有一种方法可以通过循环更改变量来引用对象名称

I've had to be writing stuff like 我不得不写一些东西

private void disable ()
{
    this.button1.Visible = false;
    this.button2.Visible = false;
    this.button3.Visible = false;
    //...
}

I've tried something like 我尝试过类似的东西

int a;
for(a=1;a==50;a++)
{
    this.buttona.Visible =false;
}

which obviously did not work 这显然没有用

Then is there a way I can refer object with a variable? 那有没有办法我可以用变量引用对象呢?

Thanks in Advance 提前致谢

You can use this code: 您可以使用以下代码:

        foreach (var c in this.Controls)
        {
            if (c is Button button)
                button.Visible = false;
        }

Or this one: 或者这个:

        for (int i = 0; i < 50; i++)
        {
            var c = this.Controls["button" + i];
            (c as Button).Visible = false;
        }

This MIGHT NOT work if you are not doing UWP, WPF, etc. If you are doing UWP, WPF, etc, this might help. 如果您未执行UWP,WPF等,则此功能可能不起作用。如果您正在执行UWP,WPF等,则可能会有所帮助。 Since all of these buttons belong to one panel (I assume so) the children or content of the panel should be an IEnumerable object, which can be processed by foreach loops. 由于所有这些按钮都属于一个面板(我认为是这样),面板的子代或内容应该是IEnumerable对象,可以通过foreach循环对其进行处理。 For example, if I have the following XAML code: 例如,如果我具有以下XAML代码:

<Grid x:Name="myGrid">
    <Button x:Name="Button1" Tag="myButton1"/>
    <Button x:Name="Button2" Tag="myButton2"/>
    <!-- ... -->
</Grid>

I can iterate through the buttons using this: 我可以使用以下方法遍历按钮:

foreach(Button button in myGrid.Children){
    if(!button.Tag.StartsWith("myButton")) continue;
    button.Visibility = Visibility.Collapsed;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM