我呢,没经历过什么大项目,对委托理解不是很深,只知道委托是方法的指针,事件是深封装的委托。今天主要分享在PowerShell中调用.NET中的委托和事件,和PowerShell中将脚本作为参数传递。
委托
首先PowerShell无委托,多数情况下是去调用一些.NET中定义的委托,这样的动态调用需要利用反射的概念:
$code=@'
using System;
using System.Reflection;
namespace PStips.NET
{
public class PSTest
{
public delegate void TestHandler(string message);
public static void TestMethod(string message)
{
Console.WriteLine(message);
}
}
}
'@
#Add-Type -TypeDefinition $code
$mi = [PStips.NET.PSTest].GetMethod('TestMethod',[Reflection.BindingFlags]'Static, Public')
$instance = [Delegate]::CreateDelegate( [PStips.NET.PSTest+TestHandler], $mi) -as [PStips.NET.PSTest+TestHandler]
$instance.DynamicInvoke('Hello PS')
事件
这可能更多的使用在PowerShell创建Winform时。下面创建一个Winform窗口,处理MouseEnter和MouseLeave,鼠标进入时背景变绿,鼠标移出时,背景变白:
Add-Type -AssemblyName System.windows.forms
$form=New-Object Windows.Forms.Form
$form.Width=200
$form.Height=200
$form.add_MouseEnter([EventHandler]{
$form.BackColor='Green'
})
$form.add_MouseLeave([EventHandler]{
$form.BackColor='White'
})
$form.ShowDialog()
脚本块
将脚本作为参数,传递给某个函数,这也稍微有点委托的味道,应当使用ScriptBlock
#定义函数
function func ([string]$str , [ScriptBlock]$script)
{
$script.Invoke($str)
}
#调用函数
func -str "pstips.net" -script {
param($myStr)
"A good site:$myStr"
}
本文链接: https://www.pstips.net/delegate-and-event.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

值得学习!