我想以编程方式在PowerShell V5.0中的类构造函数中设置公共属性。测试类有许多要填充的公共属性,具体取决于传递给类的构造函数的对象(被称为'$ something')
我认为如果我创建了一个可访问并遍历它们的公共属性名称数组,它会节省大量代码,因为设置公共属性的值只是在传递给它的$ something对象上调用相同的方法。
尝试在每个范围上使用Set-Variable cmdlet(我认为它是本地范围)。可以手动设置构造函数中的每个公共属性,但我希望能够在可能的情况下缩短它。
Class TestClass
{
[STRING]$PublicProperty
[STRING]$PublicProperty1
... ... ... #Loads more properties
[STRING]$PublicProperty50
#An array that contains name for public properties
[ARRAY]$ArrayOfPublicProperties = @("PublicProperty", "PublicProperty1"...)
TestClass($something)
{
foreach ($property in $this.ArrayOfPublicProperties)
{
Set-Variable -Name "$($property.Name)" -Scope Local -Value $($something.GetValue(#blablabla))
}
}
}
我希望能够遍历公共数组(它是粗略的代码,但它适用于我所处的情况,我不知道其他任何方式)并使用Set-Variable cmdlet设置变量。相反,它没有设置任何东西。我确信我过去做过类似的事情,以编程方式创建和设置变量等... idk。
请帮忙
Set-Variable
仅适用于常规变量,而不适用于属性。
你必须通过.psobject.properties
使用反射,这也避免了对$ArrayOfPublicProperties
辅助属性的需要:
Class TestClass
{
[string]$PublicProperty
[string]$PublicProperty1
# ...
TestClass($something)
{
# Loop over all properties of this class.
foreach ($prop in $this.psobject.Properties)
{
$prop.Value = $something.GetValue(#blablabla)
}
}
}
但是,请注意,PowerShell可以方便地通过从具有匹配属性的哈希表或(自定义)对象进行强制转换来构造和初始化对象。
警告:为此工作:
Cannot convert ... to type ...
并且还没有单个参数构造函数(隐式)键入[object]
或[hashtable]
(使用哈希表强制转换参数,[psobject]
/ [pscustomobject]
也可以)。
症状,如果不满足该条件:调用单参数构造函数。应用于您的示例(请注意,不再有显式构造函数,因为原始构造函数TestClass($something)
将击败该特征,因为$something
隐式地为[object]
-类型):
Class TestClass
{
[string]$PublicProperty
[string]$PublicProperty1
# ...
# Note: NO (explicit) constructor is defined.
}
# Construct a [TestClass] instance and initialize its properties
# from a hashtable, using a cast.
[TestClass] @{ PublicProperty = 'p0'; PublicProperty1 = 'p1'}