2014-02-20 21 views
3

我已經使用Powershell中的閉包來創建具有靜態和實例方法的類。有一個更好的方法嗎?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 

用實例「method」創建一個對象。

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 {...} 

但我不認爲這有可能創建一個使用這種方法的實例方法。

+0

您還可以將ScriptMetod成員添加到對象。 – mjolinor

+0

相關:http://stackoverflow.com/questions/18705158/powershell-create-a-class-file-to-hold-custom-objects/ –

+0

來自未來的讀者:從Powershell 5.0開始,類是一流的部分的語言。沒有更多的需要。 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_classes?view=powershell-5.1 – TurtleZero

回答

4

實例方法應該很容易使用New-Module。您的實例字段是腳本塊中的頂級變量例如:

$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() 
+0

謝謝。這是我正在尋找的。 –

+0

這似乎工作,直到有人試圖改變例如'$名稱'與setter方法。我猜是因爲'$ Name'是本地的方法?如何通過方法更新「實例範圍」中的變量? –