如何对控制数组的其他成员采取行动 [英] How to act upon a different member of control array

查看:67
本文介绍了如何对控制数组的其他成员采取行动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public void ClickHandler(Object sender, System.EventArgs e)
{
    int index;
    int curr_index;
    if (((System.Windows.Forms.Button)sender).Text == "0")
    {
        ((System.Windows.Forms.Button)sender).BackColor = System.Drawing.Color.DarkKhaki;
        index = this.List.IndexOf(sender);
        // change color of neighbor above and to the left
        curr_index = index - 33;
        foreach (System.Windows.Forms.Button butt in HostForm.Controls)
        {
            if (butt.Text == "0")
            {
                butt.BackColor = System.Drawing.Color.Black; // this turns all buttons with Text == 0 to black -- i want to turn only the button with index 33 less than butt to black
            }
        }
    }
}

推荐答案

如果您只是想更改索引-33的项目,则无需深入了解正在执行的操作的语义. ..只需执行以下操作...

Without getting into the semantics of what you''re doing... if you just want to change the item at index - 33... just do the following...

public void ClickHandler(Object sender, System.EventArgs e)
{
    int index;
    int curr_index;
    if (((System.Windows.Forms.Button)sender).Text == "0")
    {
        ((System.Windows.Forms.Button)sender).BackColor = System.Drawing.Color.DarkKhaki;
        index = this.List.IndexOf(sender);
        curr_index = index - 33;
        this.List[curr_index].BackColor = System.Drawing.Color.Black;
    }
}


代码很脏,因此可能有问题.

您使用硬编码的"0"和"33"(立即数),这将在您更改某些内容时中断程序.这对支持非常不利.太多的假设.为什么要依靠发件人位于列表List中的事实?这是不安全的.

最后,问题是所有按钮的搜索都是非递归的?您将某些按钮放在更深层次上是什么?实际上,在一个好的设计中,按钮永远不会放在Form的级别.您需要许多嵌套面板.只有递归代码才能访问您需要的所有控件.

表单上的控件太多.可用性差;表格应该更加结构化,只显示一些主题上可控制的少量控制;不要将它们全部显示在一个级别上;用户很难.例如,使用选项卡式控件.这又带来了递归搜索的问题.

另外,您需要在需要隔离数据和UI的地方混合使用它们.您需要松散耦合,因此可以轻松修改和替换UI.

—SA
The code is dirty and hence potentially problematic.

You use hard-coded "0" and "33" (immediate constants) which will break the program is you change something. This is extremely bad for support. Too many assumptions. Why you rely on the fact that the sender is in the list List? It is unsafe.

Finally, the problem is that the search for all buttons is non-recursive? What is you put some of the buttons in deeper levels? Actually, in a good designs buttons are never put at the level of the Form; you need many nested panels. Only recursive code gets access to all the controls you need.

Too many controls on the form. Poor usability; the form should be more structured showing only small manageable number of control on some topics; don''t show them all at one level; it''s hard to the user. Use tabbed control, for example. This brings back to the problem of recursive search.

Also, you mix up data and UI where you need to isolate them. You need loose coupling, so the UI could be easy to modify and replace.

—SA


这篇关于如何对控制数组的其他成员采取行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆