2

我有这个 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 的地方。

4

2 回答 2

2

在您的 C# 代码中,您可能有一个定义为 Form2 的类,它上面有控件。在您的 powershell 中,您正在加载一个香草 System.Windows.Forms.Form ,它不会有任何控件。

于 2010-10-14T15:45:32.257 回答
1

您只需要手动 .GetEnumerator() - 我不确定为什么 Powershell 没有正确展开。

$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.GetEnumerator())
    {
        $property.DisplayName
    } 
}
于 2010-10-14T17:35:56.517 回答