aは、 a が aに「バインド」されてDictionary
いる 1:1 のシナリオにうまく適合します。ここで、CheckBox は として機能し、は の値として機能します。コンパイル時に正しい型のデータを確実に処理できるように厳密に型指定できます。CheckBox
Label
Key
Label
Dictionary
// Declare this at class level
private Dictionary<CheckBox, Label> myControls = new Dictionary<CheckBox, Label>();
// ...
// Dictionary initialization goes in the ctor
// unless you generate the controls at run-time.
// If you generate controls, place it after the generation itself
myControls.Add(chk1, lab1);
myControls.Add(chk2, lab2);
// and so on...
// ...
// When you want to cycle, do this:
foreach(var controlsPair in myControls) {
// controlsPair is KeyValuePair<CheckBox, Label>
if(controlsPair.Key.Checked) continue; // SEE (*) BELOW
controlsPair.Value.Text = rng.Next(1, 7).ToString();
}
(*): コードを読むとロジックが理解しやすいので、常に条件の真偽を確認することをお勧めしますが、動作は最終的にまったく同じです。
注: このコードはどこでも動作するはずです (WinForms、WPF、Silverlight など)。