0

我正在制作一个小工具。我只想知道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
    }
}
4

3 回答 3

3

你可以这样做:

this.Controls.OfType<PictureBox>().First(x => x.Name.EndsWith(StopText.Text)).BackColor = Color;
于 2013-01-24T02:09:49.093 回答
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)
}
于 2013-01-24T02:19:30.660 回答
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 索引等)

于 2013-01-24T01:54:49.813 回答