【发布时间】:2018-10-27 02:43:42
【问题描述】:
我想在我的静态 PowerShell 5.0 类中使用 func 委托:
我很难找到一种方法来为我的委托分配其他静态类方法。
这段代码可以运行,但不是很方便。
有没有更好的方法在这里使用委托?
我需要实例化我的静态!类,只获取类型。
我尝试了注释掉的那一行,你将如何使用 .NET 类型,但它不适用于我自己的课程。
我怎样才能让我的静态类的类型在这里更优雅?
而且,顺便说一句,GetMethod() 没有接受 BindingFlags 参数,为什么?
class Demo
{
hidden static [object] Method_1([string] $myString)
{
Write-Host "Method_1: $myString"
return "something"
}
hidden static [object] Method_2([string] $myString)
{
Write-Host "Method_2: $myString"
return $null
}
hidden static [object] TheWrapper([string]$wrappedMethod, [string] $parameter)
{
# do a lot of other stuff here...
#return [System.Type]::GetType("Demo").GetMethod($wrappedMethod).CreateDelegate([Func``2[string, object]]).Invoke($parameter)
return [Demo]::new().GetType().GetMethod($wrappedMethod).CreateDelegate([Func``2[string, object]]).Invoke($parameter)
}
static DoWork()
{
Write-Host ([Demo]::TheWrapper('Method_1', 'MyMessage'))
[Demo]::TheWrapper('Method_2', 'c:\my_file.txt')
}
}
[Demo]::DoWork()
【问题讨论】:
-
[Demo]::new().GetType()->[Demo] -
第一个问题已回答,谢谢 :-)
标签: powershell class reflection delegates