Casting a scriptblock to an arbitrary delegate signature

PowerShell Team

Arild asked the following in http://arildf.spaces.msn.com/blog/cns!E99F8B43533149B0!140.entry?_c%3dBlogPart :

PSMDTAG:FAQ: Delegates – how to cast a scriptblock to an arbitrary delegate signature? ANSWER – You can’t in V1.0.

In version 1.0 Windows PowerShell only supports casting scriptblocks to delegates with the signature:

void Method(Object Sender, object e)

For instance, here is a WinForms script which uses a scriptblock delegate when a button is clicked:

  [void][Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
  $form = new-object Windows.Forms.Form
  $button = new-object Windows.Forms.Button
  $button.Dock = “fill”
  $button.Text = “Click to exit”

  ###################################
  # DELEGATE SUPPORT
  ###################################
  $button.add_click(
     {
 write-host @”
`$this is a handle to the button:
      $this”
$($this | out-string)

=====================================
`$_ is a pointer to MouseEventArgs:
      $_
$($_ | out-string)
“@

        $form.close()
     }
  )
  $form.Add_Shown(
     {$form.Activate()
     }
  )

  $form.controls.add($button)
  $form.showDialog()

This works because the delegate for the WinForms button click has the signature that we support in V1.0 (no coincidence there).

Support for delegates of any signature is definitely something we want to do ASAP (after V1.0).

Jeffrey Snover [MSFT]
Windows PowerShell/Aspen Architect
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

 

PSMDTAG:DOTNET: Delegate signatures

h.ps1

0 comments

Discussion is closed.

Feedback usabilla icon