为什么在.NET中System.IO.FileInfo
对象没有BaseName
属性,但我可以通过PowerShell使用该属性,例如:
$FolderItems = Get-ChildItem -Path "C:\" | Where-Object {$_ -isnot [IO.DirectoryInfo]}
foreach ($FolderItem in $FolderItems)
{
write-host $FolderItem.BaseName
}
Run Code Online (Sandbox Code Playgroud)
mjo*_*nor 11
Powershell为您添加了该属性.如果在fileinfo对象上运行get-member,您可以看到它是一个脚本属性,甚至是脚本本身:
get-item testfile1.txt | Get-Member BaseName | format-list
TypeName : System.IO.FileInfo
Name : BaseName
MemberType : ScriptProperty
Definition : System.Object BaseName {get=if ($this.Extension.Length -gt 0){$this.Name.Remove($this.Name.Length -
$this.Extension.Length)}else{$this.Name};}
Run Code Online (Sandbox Code Playgroud)
因为BaseName不是Property,所以它是ScriptProperty.
Name MemberType Definition
---- ---------- ----------
BaseName ScriptProperty System.Object BaseName {get=if ($this.Extension.Length -gt 0){$this.Name.Remove($this.Name.Length - $this.Extension.Length)}else{$this.Name};}
Run Code Online (Sandbox Code Playgroud)
为了澄清,它是PowerShell为您提供的从对象的其他属性派生的计算响应.它本身不是System.IO.FileInfo
对象的直接属性.当您向PowerShell请求BaseName值时,它会查看Name值,检查是否存在Extension值,然后从Name值中截断Extension值并返回结果.
编辑:令人惊讶的是,其他人在我之后2分钟回答问题的答案几乎完全相同,他们得到两倍的票数,并被标记为答案. </nerdrage>
归档时间: |
|
查看次数: |
1727 次 |
最近记录: |