Skip to content

iRon7/Use-ClassAccessors

Repository files navigation

Use-ClassAccessors

Implements class getter and setter accessors.

Syntax

Use-ClassAccessors
    [-Class <String[]>]
    [-Property <String>]
    [-Force]
    [<CommonParameters>]

Description

The Use-ClassAccessors cmdlet updates script property of a class from the getter and setter methods. Which are also known as accessors or mutator methods.

The getter and setter methods should use the following syntax:

getter syntax

[<type>] get_<property name>() {
  return <variable>
}

or:

[Object] get_<property name>() {
  return [<Type>]<variable>
}

Note

Any (single) item array will be unrolled if the [Object] type is used for the getter method.

setter syntax

set_<property name>(<variable>) {
  <code>
}

Note

A setter accessor requires a getter accessor to implement the related property.

Note

In most cases, you might want to hide the getter and setter methods using the hidden keyword on the getter and setter methods.

Examples

Example 1: Using class accessors

The following example defines a getter and setter for a value property and a readonly property for the type of the type of the contained value.

Install-Script -Name Use-ClassAccessors

Class ExampleClass {
    hidden $_Value
    hidden [Object] get_Value() {
      return $this._Value
    }
    hidden set_Value($Value) {
      $this._Value = $Value
    }
    hidden [Type]get_Type() {
      if ($Null -eq $this.Value) { return $Null }
      else { return $this._Value.GetType() }
    }
    hidden static ExampleClass() { Use-ClassAccessors }
}

$Example = [ExampleClass]::new()

$Example.Value = 42         # Set value to 42
$Example.Value              # Returns 42
$Example.Type               # Returns [Int] type info
$Example.Type = 'Something' # Throws readonly error

Parameter

Specifies the class from which the accessor need to be initialized. Default: The class from which this function is invoked (by its static initializer).

Type:
Mandatory:False
Position:Named
Default value:
Accept pipeline input:
Accept wildcard characters:False

Filters the property that requires to be (re)initialized. Default: All properties in the given class

Type:
Mandatory:False
Position:Named
Default value:
Accept pipeline input:
Accept wildcard characters:False

Indicates that the cmdlet reloads the specified accessors, even if the accessors already have been defined for the concerned class.

Type:
Mandatory:False
Position:Named
Default value:
Accept pipeline input:
Accept wildcard characters:False

Related Links

About

Implements class getter and setter accessors

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published