为什么在.NET Framework中有这样的方法?

Mar*_*mes 4 .net c# typeconverter

查看元数据我发现了这个函数:(在"System.Convert"类中)

    //
    // Summary:
    //     Calling this method always throws System.InvalidCastException.
    //
    // Parameters:
    //   value:
    //     The date and time value to convert.
    //
    // Returns:
    //     This conversion is not supported. No value is returned.
    //
    // Exceptions:
    //   System.InvalidCastException:
    //     This conversion is not supported.
    public static bool ToBoolean(DateTime value);
Run Code Online (Sandbox Code Playgroud)

为什么微软这样做?

Han*_*ant 6

Convert类非常方便处理盒装值类型.一个硬C#规则说你必须总是将它拆箱到完全相同的类型:

    object box = 42;
    long value = (long)box;  // Kaboom!
Run Code Online (Sandbox Code Playgroud)

这会生成InvalidCastException.非常不方便,特别是因为将int转换为long也不是问题.然而,在提供泛型之前,有必要在.NET 1.x中使拆箱有效,非常重要.

每种值类型都实现了IConvertable接口.这使得此代码可以解决问题:

    object box = 42;
    long value = Convert.ToInt64(box);  // No problem
Run Code Online (Sandbox Code Playgroud)

虽然这看起来非常合成,但真正的用例是从dbase读取数据.您将获得列值作为框值.显然,很可能有一个oops,其中列是Date值,程序尝试将其读作布尔值.Convert.ToBoolean(DateTime)方法确保在发生这种情况时你会发出响亮的声音.


Mik*_*sen 5

根据MSDN,Convert.ToBoolean(DateTime)留作将来使用.

他们最有可能将其添加到那里以防止向后兼容性问题,如果实施的话.但是,将DateTime转换为布尔值的方法完全超出了我的范畴.