如何获取命名空间中的所有控件?例如,我想获取System.Windows.Forms中的控件:TextBox、ComboBox等。
如何获取命名空间中的所有控件?例如,我想获取System.Windows.Forms中的控件:TextBox、ComboBox等。
命名空间中的控制这个概念有点不清楚。您可以使用反射来获取给定命名空间中从特定基类型派生的程序集中的类。例如:
class Program
{
static void Main()
{
var controlType = typeof(Control);
var controls = controlType
.Assembly
.GetTypes()
.Where(t => controlType.IsAssignableFrom(t) &&
t.Namespace == "System.Windows.Forms"
);
foreach (var control in controls)
{
Console.WriteLine(control);
}
}
}
string @namespace = "System.Windows.Forms";
var items = (from t in Assembly.Load("System.Windows.Forms").GetTypes()
where t.IsClass && t.Namespace == @namespace
&& t.IsAssignableFrom(typeof(Control))
select t).ToList();
Controls
的成员,它的类型为ControlCollection
。它本质上是一个控件列表(在底层有一些其他接口)。foreach (var control in controls)
{
if(control is TextBox)
{
(control as TextBox).Text = "Or whatever you need to do";
}
}