在Mono 2.10 REPL中玩:

csharp> string a = "true";
csharp> a.ToBoolean(CultureInfo.InvariantCulture);
{interactive}(1,4): error CS1061: Type `string' does not contain a definition fo
r `ToBoolean' and no extension method `ToBoolean' of type `string' could be foun
d (are you missing a using directive or an assembly reference?)
C:\PROGRA~1\MONO-2~1.2\lib\mono\4.0\mscorlib.dll (Location of the symbol related
 to previous error)


csharp> ((IConvertible)a).ToBoolean(CultureInfo.InvariantCulture);
true
csharp>


根据文档,System.String实现IConvertible。如果这是真的,为什么

a.ToBoolean(CultureInfo.InvariantCulture);


失败?

为什么必须将其强制转换为IConvertible才能使ToBoolean工作?

最佳答案

the documentation for ToBoolan() for string on MSDN所述:


  该成员是an explicit interface member implementation。仅当String实例强制转换为IConvertible接口时,才可以使用它。建议的替代方法是调用Convert.ToBoolean(String)方法。

10-07 13:43