Get-Date转换为字符串vs ToString() [英] Get-Date cast to string vs ToString()
问题描述
我对PowerShell的字符串嵌入语法$($ object)
的理解一直是 $ object
转换为 [System.String]
,它调用 $ object.ToString()
。但是,我在Windows 8.1上使用PowerShell 4.0,在 [DateTime]
类中注意到这个好奇的行为。
My understanding of PowerShell's string embedding syntax "$($object)"
has always been that $object
is cast to [System.String]
, which invokes $object.ToString()
. However, I've noticed this curious behavior with the [DateTime]
class using PowerShell 4.0 on Windows 8.1.
PS> $x = Get-Date
PS> $x.GetType() | select -ExpandProperty Name
DateTime
PS> $x.ToString()
2015-05-29 13:36:06
PS> [String]$x
05/29/2015 13:36:06
PS> "$($x)"
05/29/2015 13:36:06
似乎$($ object)
给出与转换为字符串相同的行为,但显然产生了与 $ object.ToString不同的结果()
。 $ x.ToString()
与intl.cpl(yyyy-MM-dd)中设置的短日期格式一致。 [String] $ x
似乎使用了en-US默认值。
It seems that "$($object)"
gives the same behavior as casting to string, but is clearly producing a different result from $object.ToString()
. $x.ToString()
is consistent with the short date format set in intl.cpl (yyyy-MM-dd). [String]$x
appears to use the en-US default.
这可能是一个bug在DateTime类中,但我更惊讶的是,将对象转换为字符串的不同方法会产生不同的结果。如果不调用 ToString()
,则将对象转换为字符串的规则是什么? DateTime类只是一个特殊情况,因为它的重载 ToString(String)
?
It is possible this is simply a bug in the DateTime class, but I'm more surprised that the different methods of converting an object to a string produce different results. What are the rules for casting an object to a string, if not calling ToString()
? Is the DateTime class simply a special case because of its overloading of ToString(String)
?
推荐答案
如果一个对象实现了 IFormattable
接口,则PowerShell将调用 IFormattable.ToString
而不是 Object.ToString
用于投射操作。对于静态 Parse
方法来说,类似的事情就是发生:如果有一个重载,比 IFormatProvider
参数更重要。
If an object implements the IFormattable
interface, then PowerShell will call IFormattable.ToString
instead of Object.ToString
for the cast operation. A similar thing happens for static Parse
method: if there is an overload with IFormatProvider
parameter, than it would be called.
Add-Type -TypeDefinition @'
using System;
using System.Globalization;
public class MyClass:IFormattable {
public static MyClass Parse(string str) {
return new MyClass{String=str};
}
public static MyClass Parse(string str,IFormatProvider fp) {
return new MyClass{String=str,FormatProvider=((CultureInfo)fp).DisplayName};
}
public string String {get;private set;}
public string FormatProvider {get;private set;}
public override string ToString() {
return "Object.ToString()";
}
string IFormattable.ToString(string format,IFormatProvider fp) {
return string.Format("IFormattable.ToString({0},{1})",format,((CultureInfo)fp).DisplayName);
}
}
'@
[String](New-Object MyClass) #Call IFormattable.ToString(null,CultureInfo.InvariantCulture)
[MyClass]'Test' #Call MyClass.Parse("Test",CultureInfo.InvariantCulture)
这篇关于Get-Date转换为字符串vs ToString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!