开发者

C# TypeConverters and IsValid

I am trying to use System.ComponentModel.TypeConverter to cast a bunch of System.Strings to different types. These Strings may or may not be in a valid format for the TypeConverter, so I'd like to find a way to check their validity before attempting the type conversion (to avoid having to rely on catching a System.FormatException to indicate that the String is not in the correct format).

Great, that's why TypeConverters have an IsValid() method, right? Well I'm running into a problem where IsValid() will return true, but when I call ConvertFromString(), it throws an exception. Here is some code to 开发者_C百科reproduce the issue:

        System.ComponentModel.DateTimeConverter DateConversion = 
            new System.ComponentModel.DateTimeConverter();

        String TheNumberZero = "0";

        if (DateConversion.IsValid(TheNumberZero))
            Console.WriteLine(DateConversion.
                ConvertFromString(TheNumberZero).ToString());
        else
            Console.WriteLine("Invalid.");

When I run this, the line

Console.WriteLine(DateConversion.
    ConvertFromString(TheNumberZero).ToString());

throws a System.FromatException with the message

0 is not a valid value for DateTime.

What is the purpose of the IsValid() method if not to check the conversion input before attempting a type conversion? Is there some way I can check the String's validity short of having to catch the FormatException?


The documentation is your friend:

The IsValid method is used to validate a value within the type rather than to determine if value can be converted to the given type. For example, IsValid can be used to determine if a given value is valid for an enumeration type. For an example, see EnumConverter.

You can write your own WillConvertSucceed method by wrapping the ConvertTo and ConvertFrom methods in exception blocks.


This is a code example of what was suggested by ck.
Typically when you actually need to know if the parse of a value type will work this is the method to use.

        DateTime convertedDate;
        string zero = "0";

        if (!DateTime.TryParse(zero, out convertedDate))
        {
            throw new InvalidCastException(string.Format(
                "Attempted Invalid Cast of {0} to DateTime",zero));
        }


Sounds like TryParse on Int32, DateTime, Decimal etc. might be a bit more useful and efficient.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜