gpt4 book ai didi

class - Powershell 类

转载 作者:行者123 更新时间:2023-12-02 04:45:05 26 4
gpt4 key购买 nike

我在 Powershell 中使用闭包来创建具有静态方法和实例方法的类。有更好的方法吗?

使用静态“方法”创建和对象。

function person_get_type {
return 'Person'
}

function make_person {
param
(
[parameter(mandatory=$true)][string]$name)

$properties = @{'name'=$name;'get_type'=$null}
$person = New-Object –TypeName PSObject –Prop $properties
$person.get_type = ${function:person_get_type}
return $person
}

$person = make_person -name 'James'
$type = $person.get_type.InvokeReturnAsIs()
Write-Host $type

使用实例“方法”创建对象。

function dog_get_type {
return 'Dog'
}

function dog_make_get_name{
param
(
[Parameter(Mandatory=$true)][System.Management.Automation.PSObject]$self
)
return {return $self.name}.GetNewClosure()
}

function dog_make_set_name{
param
(
[Parameter(Mandatory=$true)][System.Management.Automation.PSObject]$self
)
return {param([parameter(mandatory=$true)][string]$name) $self.name = $name}.GetNewClosure()
}

function make_dog {
param
(
[parameter(mandatory=$true)][string]$name
)

$properties = @{'name'=$name;'get_type'=$null;'get_name'=$null;'set_name'=$null}
$dog = New-Object –TypeName PSObject –Prop $properties
$dog.get_type = ${function:dog_get_type}
$dog.get_name = dog_make_get_name -self $dog
$dog.set_name = dog_make_set_name -self $dog
return $dog
}

$dog = make_dog -name 'Spot'
$name = $dog.get_name.InvokeReturnAsIs()
Write-Host $name

$dog.set_name.Invoke("Paws")
$name = $dog.get_name.InvokeReturnAsIs()
Write-Host $name

$stuff = @($person,$dog)
foreach($thing in $stuff) {
Write-Host $thing.get_type.InvokeReturnAsIs()
}

我已经看到可以在哪里使用这种方法:

$object = New-Module -AsCustomObject -ScriptBlock {...}

但我不认为可以使用这种方法创建实例方法。

最佳答案

使用New-Module实例方法应该很容易。您的实例字段是脚本 block 中的顶级变量,例如:

$sb = {
param($theName,$theAge,$theBreed)

$Name = $theName
$Age = $theAge
$Breed = $theBreed

$global:NumDogs++

function Description {
"Dog named $Name, age $Age, breed $Breed"
}

function get_NumDogs {
"Total number of dogs is $NumDogs"
}
Export-ModuleMember -Variable Name,Age,Breed -Function Description,get_NumDogs
}


$dog1 = New-Module $sb -AsCustomObject -ArgumentList 'Mr. Bill',1,'Jack Russell'
$dog1.Name
$dog1.Age
$dog1.Description()
$dog1.get_NumDogs()
$dog2 = New-Module $sb -AsCustomObject -ArgumentList Fluffy,3,Poodle
$dog2.Name
$dog2.Age
$dog2.Description()
$dog2.get_NumDogs()

关于class - Powershell 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21920978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com