What is the point of Convert.ToDateTime(bool)?

后端 未结 3 836
时光取名叫无心
时光取名叫无心 2020-12-20 11:42

I was doing some type conversion routines last night for a system I am working on. One of the conversions involves turning string values into their DateTime equivalents.

相关标签:
3条回答
  • 2020-12-20 11:52

    It makes sense because ToDateTime is part of the IConvertible interface implemented by bool. If you look in reflector you will see that it throws an InvalidCastException.

    Update (from Convert):

    public static DateTime ToDateTime(bool value)
    {
        return ((IConvertible) value).ToDateTime(null);
    }
    
    0 讨论(0)
  • 2020-12-20 11:57

    If you look closely, most of the overloads are invalid and will throw an InvalidCastException.

    It has to implement all of the casts as it implements IConvertible and this is the only way to do it correctly.

    0 讨论(0)
  • 2020-12-20 12:06

    I think it's there for completeness and that you get an explicit InvalidCastException when calling Convert.ToDateTime with an object that is a bool.

    If you look at all the members of Convert, you can see that overloads have been included to accept all the basic types for conversion to each of the other basic types, with InvalidCastExceptions being thrown when there is no sensible conversion.

    I guess they thought this would be more meaningful than just not having the overloads there at all.

    0 讨论(0)
提交回复
热议问题