无法将'string'类型转换为'System.Windows.Forms.Button'

-2 c# casting visual-studio-2013

foreach(Control c in tabAppreciation.Controls)
        {
            if(c is Button)
            {
                if((Button)c.Text.ToString()==0)
                {
                    c.BackColor = Color.Green;
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

我收到此错误:无法将类型'string'转换为'System.Windows.Forms.Button'

我想比较每个按钮的文字和一些东西,如果匹配,改变按钮的颜色,但似乎我没有正确做到...有人可以帮助我吗?

Ste*_*eve 5

您可以将代码更改为更简单的代码

foreach(Button b in tabAppreciation.Controls.OfType<Button>())
{
    if(b.Text=="0")
    {
       b.BackColor = Color.Green;
    }
}
Run Code Online (Sandbox Code Playgroud)

这将枚举tabAppreciation控件集合中Button类型的所有控件,并且您的循环是强类型的,因此您不再需要测试Is Button.另请注意,该Text属性已经是一个字符串,因此应用ToString()没有意义.最后一个字符串应该与一个字符串进行比较(将零写在双引号之间,而不是单引号表示一个字符)

仅供参考:OfType<T>如果尚未使用,则需要using System.Linq;在代码文件的顶部添加指令.