0

我有一个清单

List<Control> inputBoxes = new List<Control>();

我在其中添加了组合框和文本框。

我可以设置 text 属性, inputBoxes[0].GetType().GetProperty("Text").SetValue(inputBoxes[0], "ABC", null); 但如何将项目添加到组合框并选择它们?

我可以inputBoxes[0].GetType().GetMethod()以某种方式使用吗?

4

1 回答 1

0

为什么你使用反射来简单地设置一个属性?

您可以使用它更有效且不易出错:

inputBoxes.OfType<TextBox>().ElementAt(0).Text = "ABC";

如果要将项目添加到一个(或多个)组合框:

var combos =  inputBoxes.OfType<ComboBox>();
foreach(ComboBox combo in combos)
{
    // add items here or set their DataDource, for example:
    string[] installs = new string[]{"Typical", "Compact", "Custom"};
    combo.Items.AddRange(installs);
}

using System.Linq请注意,您需要添加OfType

于 2012-09-16T19:31:33.563 回答