Set-Variable
only works with regular variables, not with properties.
You must use reflection via .psobject.properties
, which also obviates the need for the $ArrayOfPublicProperties
helper property:
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)
}
}
}
Note, however, that PowerShell conveniently allows constructing and initializing objects by a way of a cast from a hashtable or (custom) object that have matching properties.
Caveats: For this to work:
- the class must either have NO constructor (i.e., implicitly support only the parameter-less default constructor),
OR, if there are constructors:
- a parameter-less constructor must exist too.
- Symptom, if that condition isn't met: a type-conversion error:
Cannot convert ... to type ...
- AND there's not also a single-argument constructor (implicitly) typed
[object]
or [hashtable]
(with a hashtable cast argument, [psobject]
/ [pscustomobject]
is fine, however).
- Symptom, if that condition isn't met: the single-argument constructor is called.
The set of property names of the input hashtable / object must be a subset of the target class' properties; in other words: the input object mustn't contain properties that aren't also present in the target class, but not all target-class properties must be present.
Applied to your example (note that there's no longer an explicit constructor, because the original constructor, TestClass($something)
, would defeat the feature, due to $something
being implicitly [object]
- typed):
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'}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…