zoukankan      html  css  js  c++  java
  • PowerTip of the DayAcessing Function Parameters by Type

    原文地址:

    http://app.en25.com/e/es.aspx?s=1403&e=5125&elq=52bc48204cc748d58a54ab9a57b6b796

    原文:

    Adding parameters to your functions is fairly easy. You can add a param() block and specify the parameters. But what if you wanted to assign values to different parameters based solely on type? Let's say you want a function that accepts both numbers and text, and depending on which type you submitted, choose a parameter. Here is how you can do that:

    function Test-Binding {
      [
    CmdletBinding(DefaultParameterSetName='Name')]
     
    param(
        [
    Parameter(ParameterSetName='ID', Position=0, Mandatory=$true)]
         [
    Int]
        
    $id,
        [
    Parameter(ParameterSetName='Name', Position=0, Mandatory=$true)]
         [
    String]
        
    $name
      )
     
     
     
    $set = $PSCmdlet.ParameterSetName
      "You selected parameterset $set"
     
     
    if ($set -eq 'ID') {
       
    "The numeric ID is $id"
      } else {
       
    "You entered $name as a name"
      }
    }

    Try this:

    Test-Binding 12

    Test-Binding "Hello"

    Test-Binding

    翻译:

    方法里添加参数是很简单的。你可以在Param()代码块里添加指定的参数。但是如果想根据参数的类型来选择参数值到底赋给哪个参数呢?假如,有一个方法可以接收两个参数:NumbersText,根据你提交的内容,选择哪个参数,以下是实现方法:

    function Test-Binding {
      [
    CmdletBinding(DefaultParameterSetName='Name')]
     
    param(
        [
    Parameter(ParameterSetName='ID', Position=0, Mandatory=$true)]
         [
    Int]
        
    $id,
        [
    Parameter(ParameterSetName='Name', Position=0, Mandatory=$true)]
         [
    String]
        
    $name
      )
     
     
     
    $set = $PSCmdlet.ParameterSetName
      "You selected parameterset $set"
     
     
    if ($set -eq 'ID') {
       
    "The numeric ID is $id"
      } else {
       
    "You entered $name as a name"
      }
    }

    调用方法:

    Test-Binding 12

    Test-Binding "Hello"

    Test-Binding

    笔记:

    这个方法适用于动态参数的赋值,前提是参数的类型必须都不相同,否则会有歧义。

  • 相关阅读:
    AdvStringGrid使用小结
    svn提示out of date的解决方法
    delphi之socket通讯
    Delphi的Socket编程步骤
    C++ Socket编程步骤
    centos7安装docker
    centos7安装指南
    UltraISO制作U盘启动盘
    浅谈linux 文件的三个时间
    自动配置zabbix-agent
  • 原文地址:https://www.cnblogs.com/aspnetx/p/1768537.html
Copyright © 2011-2022 走看看