字符串a; a.ToBoolean(...)&IConvertible

Nao*_*aem 3 c# interface

在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>
Run Code Online (Sandbox Code Playgroud)

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

a.ToBoolean(CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

失败?

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

svi*_*ick 7

正如MSDN上的for 文档ToBoolan()string所述:

该成员是显式接口成员实现.它只能在将String实例强制转换为IConvertible接口时使用.建议的替代方法是调用该Convert.ToBoolean(String)方法.