我有这个 C# 代码来枚举 Form 实例的控件:
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
Form2 form2 = new Form2();
foreach (Control control in form2.Controls)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(control);
foreach (PropertyDescriptor property in properties)
{
textBox1.Text += (property.Name + Environment.NewLine);
}
}
}
这列出了 TextBox 中 Form form2 的所有控件名称。这是我在 PowerShell 中重现此代码的尝试:
$form = New-Object System.Windows.Forms.Form
foreach($control in $form.Controls)
{
$properties =
[System.ComponentModel.TypeDescriptor]::GetProperties($control)
foreach($property in $properties)
{
$property.Name
}
}
但这不起作用。$form.Control 似乎是空的,所以永远不会进入 foreach 循环。如何使上述 C# 代码在 PowerShell 中工作?
[编辑 1]
上面的代码显然有一个没有控件的表单。这是更新的 PowerShell 代码,其中包含一个添加到其 Controls 集合中的 Button 表单,但(似乎)与未枚举 Controls 集合的结果相同:
$form = New-Object System.Windows.Forms.Form
$button = New-Object System.Windows.Forms.Button
$form.Controls.Add($Button)
$form.Controls.Count
foreach($control in $form.Controls)
{
$properties =
[System.ComponentModel.TypeDescriptor]::GetProperties($control)
foreach($property in $properties)
{
$property.DisplayName
}
}
[编辑 2]
如果我检查 $property 类型:
foreach($property in $properties)
{
$property.GetType().FullName
}
GetType() 返回:
System.ComponentModel.PropertyDescriptorCollection
我期望 PropertyDescriptor 的地方。