使用方法remove_Click
(remove_MyEvent
在下面的示例中)和存储在变量中的脚本块。这是示例:
# A static class with a sample event
Add-Type @'
using System;
public static class TestEvents {
public static event EventHandler MyEvent;
public static void InvokeEvent()
{
if (MyEvent != null) {
MyEvent(null, null);
}
}
}
'@
# Script used as event handler, it prints "In event handler."
$script = {
Write-Host "In event handler."
}
# Add the script handler
[TestEvents]::add_MyEvent($script)
# Test: it writes "In event handler."
[TestEvents]::InvokeEvent()
# Remove the script handler
[TestEvents]::remove_MyEvent($script)
# Test: it does not write write "In event handler." because the handler has been removed
[TestEvents]::InvokeEvent()
请注意,在 PS V2 CTP3 中存在问题713174
,但似乎已解决,因此[EventHandler]
甚至不需要转换为。但也要记住这个技巧。