【问题标题】:WinForm inside hashtable哈希表内的 WinForm
【发布时间】:2020-01-29 17:58:48
【问题描述】:

我可以在哈希表中设置表单元素:

$Hash = @{}

$Hash.Main = New-Object System.Windows.Forms.Form
$Hash.Main.Left = 0
$Hash.Main.Top = 0
...
$Hash.Label = New-Object System.Windows.Forms.Label
$Hash.Label.Left = 0
$Hash.Label.Top = 0
...
$Hash.Panel = New-Object System.Windows.Forms.Panel
$Hash.Panel.Left = 0
$Hash.Panel.Top = 0
...

我怎样才能在哈希表中写同样的东西?我试着让它好像可以。它有效。但是这个语法正确吗?

$Hash = @{

   Main = [System.Windows.Forms.Form] @{

      Left = 0
      Top = 0
      ...
   }

   Label = [System.Windows.Forms.Label] @{

      Left = 0
      Top = 0
      ...
   }

   Panel = [System.Windows.Forms.Panel] @{

      Left = 0
      Top = 0
      ...
   }
}

谢谢

【问题讨论】:

  • 也许我遗漏了一些东西,但为什么不采取第二个代码块并尝试一下看看它是否有效或产生语法错误?

标签: winforms powershell hashtable


【解决方案1】:

是的,这个语法是正确的:

Creating Objects from Hash Tables

从 PowerShell 3.0 开始,您可以从哈希创建对象 属性和属性值表。

语法如下:

[<class-name>]@{
  <property-name>=<property-value>
  <property-name>=<property-value>
  …
}

此方法仅适用于具有 null 构造函数的类, 也就是没有参数的构造函数。 对象属性 必须是publicsettable

如需了解更多信息,请参阅about_Object_Creation

检查第一个条件(没有参数的构造函数):

[System.Drawing.Font],        ### does not have empty constructor 
[System.Windows.Forms.Form],
[System.Windows.Forms.Label],
[System.Windows.Forms.Panel] |
    Where-Object { 
        'new' -in ( $_ | 
            Get-Member -MemberType Methods -Static | 
                Select-Object -ExpandProperty Name ) -and
        $_::new.OverloadDefinitions -match ([regex]::Escape('new()'))
    } | Select-Object -ExpandProperty FullName
System.Windows.Forms.Form
System.Windows.Forms.Label
System.Windows.Forms.Panel

检查后一个条件(对象属性必须是公共的和可设置的):

[System.Windows.Forms.Form],
[System.Windows.Forms.Label],
[System.Windows.Forms.Panel] | 
    ForEach-Object {
        @{ $_.FullName = ( 
            $_.GetProperties('Instance,Public') | Where-Object CanWrite |
                Select-Object -ExpandProperty Name | Sort-Object
           )
        }
    }
Name                           Value
----                           -----
System.Windows.Forms.Form      {AcceptButton, AccessibleDefaultActionDescription, Acc...
System.Windows.Forms.Label     {AccessibleDefaultActionDescription, AccessibleDescrip...
System.Windows.Forms.Panel     {AccessibleDefaultActionDescription, AccessibleDescrip...

将上述两个代码 sn-ps 放在一起是一项微不足道的任务……

【讨论】:

    猜你喜欢
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2013-04-18
    • 2015-07-29
    • 2013-06-06
    • 2023-03-27
    • 2012-11-10
    相关资源
    最近更新 更多