TextBox.Text [1 | 2] - > PictureBox {1 | 2} .Color = SomeColor?

时间:2013-01-24 01:50:54

标签: c# .net c#-4.0 variables

我正在制作一个小工具。我只是想知道下面代码中的switch是否是实现这一目标的最快/最好的方法?在PHP中,我会像$Stop{int Stop} -> $BackColor = "Color"

一样动态引用变量名

CSSGM

public void Populate(Color Color, int Stop)
{
    Colour.BackColor = Color;             // Bottom left - PictureBox
    Hex.Text = ARGBToHex(Color.ToArgb()); // Hex (#703919) - TextBox
    Red.Text = Color.R.ToString();        // Red (153) - TextBox
    Green.Text = Color.G.ToString();      // Green (180) - TextBox
    Blue.Text = Color.B.ToString();       // Blue (209) - TextBox
    Alpha.Text = "100";                   // Alpha (100) - TextBox
    StopText.Text = Stop.ToString();      // Read-only (1) - TextBox
    switch(Convert.ToInt16(StopText.Text))
    {
        case 1: Stop1.BackColor = Color; break;  // Small light blue rectangle - PictureBox
        case 2: Stop2.BackColor = Color; break;  // Small dark blue rectangle - PictureBox
    }
}

3 个答案:

答案 0 :(得分:3)

你可以这样做:

this.Controls.OfType<PictureBox>().First(x => x.Name.EndsWith(StopText.Text)).BackColor = Color;

答案 1 :(得分:1)

如果您重新排序分配顺序,尤其是StopText.TextStopX.BackColor,则可以让您的生活更轻松。

然后更改您的使用情况并传递PictureBox而不是无意义的数字(1或2):

public void Populate(Color Color, PictureBox Stop)
{
  Colour.BackColor = Color;             // Bottom left - PictureBox
  Hex.Text = ARGBToHex(Color.ToArgb()); // Hex (#703919) - TextBox
  Red.Text = Color.R.ToString();        // Red (153) - TextBox
  Green.Text = Color.G.ToString();      // Green (180) - TextBox
  Blue.Text = Color.B.ToString();       // Blue (209) - TextBox
  Alpha.Text = "100";                   // Alpha (100) - TextBox

  Stop.BackColor = Color;
  StopText.Text = Stop.Name.Substring(Stop.Name.Length - 1, 1)
}

答案 2 :(得分:0)

而不是

StopText.Text = Stop.ToString();
switch(Convert.ToInt16(StopText.Text))
{
    case 1: Stop1.BackColor = Color; break;
    case 2: Stop2.BackColor = Color; break;
}

为什么不

//have an array of 2 Stops called Stops
StopText.Text = Stop.ToString();
if (Stop < Stops.Length)
{
  Stops[Stop].BackColor = Color;
}

(并确保一致地使用0或1索引等)