Function overloading in PowerShell

前端 未结 4 1670
温柔的废话
温柔的废话 2020-12-15 16:11

Can you overload functions in PowerShell?

I want to my function to accept a string, array or some switch.

An example of what I want:

  • Backup-Use
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 16:37

    1) Build a class...

    class c1 { 
        [int]f1( [string]$x ){ return 1 } 
        [int]f1( [int ]$x ){ return 2 }
        }
    

    1+) Use STATIC METHODS if you prefer to call them without instantiation...

    class c1 { 
        static [int] f1( [string]$x ){ return 1 } 
        static [int] f1( [int]$x ){ return 2 } 
        }
    

    2) Call the methods in class or object... overload works OK

    $o1 = [c1]::new()
    o1.f1( "abc" ) ~> returns 1
    o1.f1( 123 )   ~> returns 2
    

    -OR-


    [c1]::f1( "abc" ) ~> returns 1
    [c1]::f1( 123 )   ~> returns 2
    

    3) If (like me)
    you want to have "Overloaded Functions" placed in a libraries...
    so your users can use them transparently...
    from code or from Interactive Command Line (REPL)...

    the closest I could came to
    "Overloading functions in Powershell"
    was something like this:

    function Alert-String() { [c1]::f1( "abc" ) }
    function Alert-Strings(){ [c1]::f1( 123 ) }
    function Alert-Stringn(){ [c1]::f1( 123 ) }
    

    Maybe in PS-Core v8??? ;-)

    Hope it helps...

提交回复
热议问题