Welcome to MSDN Blogs Sign in | Join | Help

Casting a scriptblock to an arbitrary delegate signature

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

Published Monday, July 24, 2006 9:12 PM by PowerShellTeam
Filed under: ,

Attachment(s): h.ps1

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Casting a scriptblock to an arbitrary delegate signature

Is there any way to hack around this using inline C#? I tried but I couldn't make it work.
Monday, July 24, 2006 8:37 PM by Scott Yost

# re: Casting a scriptblock to an arbitrary delegate signature

scyost: I think I may have a solution to work around this. I'll probably blog about it later today.
Tuesday, July 25, 2006 4:43 AM by Arild Fines

# re: Casting a scriptblock to an arbitrary delegate signature

We were just about ready to ask about this.

Thanks Jeffrey
Tuesday, July 25, 2006 4:54 PM by Jim Vierra

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker