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

时间:2008-12-11 09:50:55

标签: .net powershell oop types

如果我想在powershell中创建一个.NET对象,我会写如下内容:

[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 个答案:

答案 0 :(得分:3)

当您在给定类上使用静态方法时,将使用括号。在实例化特定类的新对象时,不需要括号。

括号也用于将变量转换为某种类型

PS C:\> $i = [int]"1"
PS C:\> $i.gettype().Name
Int32
PS C:\> $j = "1"
PS C:\> $j.gettype().Name
String
PS C:\>

答案 1 :(得分:2)

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

// 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

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

答案 2 :(得分:0)

是的,你提出问题的方式有点令人困惑。 System.Xml.XmlDocument和System.String被定义为类,因此您可以为每个类使用new-object来创建该特定类型的对象。

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

答案 3 :(得分:0)

我看,可能,我的问题有点令人困惑。

我要问的是:括号和冒号的语法是什么原因?为什么微软没有像C#那样定义它 - 一切都是由点分开的?

当我看到以下内容(我实际上是想引起注意)时出现了问题:

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

显然,有时候不需要括号/冒号语法,为什么它甚至存在?

答案 4 :(得分:0)

我猜新对象只是将它传递给Activator,后者期望一个以句点分隔的名称 - powershell实际上并没有管理那部分。

答案 5 :(得分:0)

在行的情况下:

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

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

$doc = new-object -typename "TypeThatDoesntExsit" 

它会显示错误,因为它会尝试将类型动态地解析为字符串。