【问题标题】:How to use delegates inside a static PowerShell class?如何在静态 PowerShell 类中使用委托?
【发布时间】: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


【解决方案1】:

您不需要创建[demo] 的实例,因为[demo] 是类的实际类型。此外,您可以将委托类型更简单地编写为[Func[string,object]]。这将TheWrapper 方法的主体简化为

return [Demo].GetMethod($wrappedMethod).CreateDelegate([Func[string, object]]).Invoke($parameter)

但在 PowerShell 中执行此操作的一种更简单的方法是通过将方法的名称传递给 '.' 来获取方法。运算符然后调用结果:

return [demo]::$wrappedMethod.Invoke($parameter)

在 PowerShell 中,'.' 的右侧运算符不需要是常数。您可以使用导致方法(或属性)名称的表达式进行检索。

【讨论】:

  • 使用[demo]::$wrappedMethod.Invoke($parameter)而不是[demo]::$wrappedMethod($parameter)有什么特别的理由吗?
  • 非常感谢 :-) 我总是忘记用脚本语言实现这样的事情是多么简单,但是显式使用 C# 委托不是更安全的方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 2011-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
相关资源
最近更新 更多