问题描述
如何发布带有点字符的哈希表关键字,如FlatAppearance.BorderSize
,以确保其正确?
$Button = [System.Windows.Forms.Button] @{
# This is not a valid entry
FlatAppearance.BorderSize = 0
}
$Button = [System.Windows.Forms.Button] @{
# This is not a valid entry too
"FlatAppearance.BorderSize" = 0
}
$Button = [System.Windows.Forms.Button] @{
# This is not a valid entry too too
FlatAppearance = @{ BorderSize = 0 }
}
当然,我可以这样写
$Button = [System.Windows.Forms.Button] @{}
$Button.FlatAppearance.BorderSize = 0
但是,在哈希表中写入会更方便。但如何做到呢?谢谢
推荐答案
由于Button
类型的.FlatAppearance
属性是FlatButtonAppearance
类型,因此在这种情况下没有好的解决方案,因为FlatButtonAppearance
类型没有公共的、无参数的构造函数。
如果是这样,您将能够编写:
using namespace System.Windows.Forms
$Button = [Button] @{
# !! This is how you would generally do it, but
# !! IN THIS CASE IT DOESN'T WORK, due to lack of an appropriate constructor.
FlatAppearance = [FlatButtonAppearance] @{ BorderSize = 0 }
}
上述语法类似于C#的对象初始值设定项语法,将在下一节中介绍。
Object初始值设定项语法:
若要从哈希表( 目标类型必须具有构造函数(其中可能是),即: 类型的公共属性的名称必须与哈希表条目的键匹配,并且条目的值必须具有与目标属性相同或兼容的类型。 这允许PowerShell只需调用 注意:PowerShell v3+中提供的此类强制转换实际上是语法糖,用于调用 除了查阅类型文档外,您还可以通过调用PowerShell提供的不带括号的静态 确定类型的公共可写实例属性: 这篇关于带指针的哈希表密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!@{ ... }
)或预先存在的[pscustomobject]
实例转换为类型文字([...]
),要执行隐式构造(隐式创建实例),然后进行多属性初始化,必须满足以下先决条件:new SomeType()
(PowerShell语法中的[SomeType]::new()
),然后从同名的哈希表条目中分配公共属性值,即可在后台创建一个实例。New-Object
带有-Property
参数的cmdlet;只有后者在v2中有效。::new
方法(()
):PS> [System.Windows.Forms.FlatButtonAppearance]::new
# NO OUTPUT, which means the type has no public constructors at all.
# [ProcessStartInfo] has several public constructors, among them
# a public parameterless one, so you *can* initialize it by hashtable.
PS> [System.Diagnostics.ProcessStartInfo]::new
OverloadDefinitions
-------------------
System.Diagnostics.ProcessStartInfo new()
System.Diagnostics.ProcessStartInfo new(string fileName)
System.Diagnostics.ProcessStartInfo new(string fileName, string arguments)
PS> [System.Windows.Forms.FlatButtonAppearance].GetProperties('Public, Instance') |
? CanWrite | Select-Object Name, PropertyType
Name PropertyType
---- ------------
BorderSize System.Int32
BorderColor System.Drawing.Color
CheckedBackColor System.Drawing.Color
MouseDownBackColor System.Drawing.Color
MouseOverBackColor System.Drawing.Color