代码之家  ›  专栏  ›  技术社区  ›  Dave

关于powershell脚本语言中使用.NET类型的一致性

  •  0
  • Dave  · 技术社区  · 17 年前

    [System.Reflection.Assembly]::LoadWithPartialName("System.Xml") | out-null"
    $doc = new-object -typename System.Xml.XmlDocument"
    

    如果要调用静态.Net方法,请使用类似于以下行的命令:

    $path = [System.String]::Format("{0} {1}", "Hello", "World")
    

    我看不出这背后有什么规则。如果它在第一个示例中有效,为什么我不能使用 System.String.Format

    6 回复  |  直到 17 年前
        1
  •  3
  •   Andy Schneider    17 年前

    括号还用于将变量强制转换为特定类型

    PS C:\> $i = [int]"1"
    PS C:\> $i.gettype().Name
    Int32
    PS C:\> $j = "1"
    PS C:\> $j.gettype().Name
    String
    PS C:\>
    
        2
  •  2
  •   Tomalak    17 年前

    我相信你在这里混淆了类型和成员。

    // type "Assembly" in the "System.Reflection" namespace
    [System.Reflection.Assembly] 
    
    // member method "LoadWithPartialName" of type "Assembly"
    [System.Reflection.Assembly]::LoadWithPartialName 
    
    // type "String" in the "System" namespace
    [System.String] 
    
    // member method "Format" of type "String"
    [System.String]::Format
    

    它正在正常工作。你的困惑来自哪里?

        3
  •  0
  •   Marco Shaw    17 年前

    是的,你的问题措辞有点混乱。 System.Xml.XmlDocument和System.String被定义为类,因此您可以为它们中的每一个使用新对象来创建特定类型的对象。

    仅仅因为你有“foo.bar.joe”,并不意味着你在做与“abc.def”不同的事情。这两个类都是有效的类,只是碰巧它们具有不同的名称空间长度/定义。

        4
  •  0
  •   dave dave    17 年前

    我明白了,我的问题可能有点困惑。

    我想问的是:为什么用括号和冒号这样的语法?为什么微软没有用C语言来定义它——所有的东西都用点分隔?

    $doc = new-object -typename "System.Xml.XmlDocument"
    

    显然,有时不需要方括号/冒号语法,那么它为什么会存在呢?

        5
  •  0
  •   Jimmy    17 年前

    我猜新对象只是将其传递给Activator,Activator需要一个以句点分隔的名称——powershell实际上并不管理该部分。

        6
  •  0
  •   Szymon Rozga    17 年前

    如果是直线:

    $doc = new-object -typename "System.Xml.XmlDocument"
    

    不需要括号,因为参数-typename的类型为string。从技术上讲,我们可以这样称呼它:

    $doc = new-object -typename "TypeThatDoesntExsit" 
    

    推荐文章