문제

Looking at metadata I found this function: (in the "System.Convert" class)

    //
    // 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);

Why Microsoft do this?

도움이 되었습니까?

해결책

The Convert class is very handy to deal with boxed value types. A hard C# rule says that you must always unbox it to the exact same type:

    object box = 42;
    long value = (long)box;  // Kaboom!

That generates an InvalidCastException. Pretty inconvenient, especially since converting an int to a long is never a problem otherwise. It was however necessary to make unboxing efficient, very important in .NET 1.x before generics were available.

Every value type implements the IConvertable interface. Which make this code work to solve the problem:

    object box = 42;
    long value = Convert.ToInt64(box);  // No problem

While this looks pretty synthetic, the real use case is reading data from a dbase. You'll get the column values as boxed values. And clearly it is very possible to have an oops where a column is a Date value and the program tries read it as a Boolean. The Convert.ToBoolean(DateTime) method ensures that you'll get a loud bang when that happens.

다른 팁

According to MSDN, Convert.ToBoolean(DateTime) is reserved for future use.

They've most likely added it in there to prevent backwards compatibility issues down the road if this is implemented. However, what converting a DateTime to a Boolean means, is completely beyond me.

This is a part of the static Convert class. It is no doubt there for symmetry with the other methods provided: there's a Convert.ToDateTime that converts things to DateTimes, and there's a Convert.ToSTring that's happy to convert DateTimes to Strings. Rather than define each conversion method to only take the arguments it understands, each method has a general set of overloads and some of them are just stubs.

Because someone at Microsoft decided that System.Convert needed to have a method to convert to/from every primitive type, regardless of whether or not a conversion was even possible.

Notice that there are several methods like this:

Convert.ToDateTime(Boolean value)
Convert.ToBoolean(Char value)

and most of the ToChar methods.

So this throws a error Link:

    DateTime actualdate;
    bool canNotConvert = Convert.ToBoolean(actualdate);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top