数组对于您的需求来说太原始了。正如@timur 建议的那样,您可以创建一个Dictionary<TKey,TValue>,其中您的“TKey”为string,您的“TValue”为object。你可以这样使用它:
// Create a new dictionary of objects, with string keys.
//
Dictionary<string, object> mycode=
new Dictionary<string, object>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
mycode.Add("txt1", "Hello");
mycode.Add("rb1", 2);
您可以使用实际的控件引用而不是它们的名称作为字符串。所有控件都继承自Control 类。所以你可以使用Dictionary<Control, object>。
在这里,我为您提供一个简单的示例,其中包含一个具有 TextBox (textBox1)、一个 NumericUpDown (numericUpDown1) 和一个按钮 (button1) 的表单。
Dictionary<Control, object> myDictionary = new Dictionary<Control, object>();
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (myDictionary.ContainsKey((Control)sender))
myDictionary[(Control)sender] = ((NumericUpDown)sender).Value;
else
myDictionary.Add((Control)sender, ((NumericUpDown)sender).Value);
}
private void button1_Click(object sender, EventArgs e)
{
if (myDictionary.ContainsKey(numericUpDown1))
textBox1.Text = ((decimal)myDictionary[numericUpDown1]).ToString();
}
用这种方法你必须做很多演员,你必须小心。