Is there a try Convert.ToInt32… avoiding exceptions

前端 未结 7 1770
长发绾君心
长发绾君心 2020-12-08 18:51

I\'d like to know if there is a \"safe\" way to convert an object to an int, avoiding exceptions.

I\'m looking for something like public static bo

7条回答
  •  有刺的猬
    2020-12-08 19:27

    Spurring from the comments. The response is no. You can't do what Convert.ToInt32(object) does without having throwed exceptions. You can do something similar (and you already did it). The only thing I would optimize is the case of value already an int.

    if (value is int) 
        return (int)value;
    

    You can't do as Convert.ToInt32(object) because Convert.ToInt32(object) doesn't simply test if value is short, int, long, ushort, ... and then cast them. It checks if the value is IConvertible. If yes it uses the IConvertible.ToInt32. Sadly the interface IConvertible is quite poor: it doesn't have non-throwing methods (IConvertible.Try*)

    While stupid (but perhaps not too much), someone could make for example a UnixDateTime struct: (UnixTime is the number of seconds from midnight 1970-01-01), where the IConvertible.ToInt32 returns this number of seconds, while the ToString() returns a formatted date. All the int.TryParse(value.ToString(), out parsed) would choke, while the Convert.ToInt32 would work flawlessly.

提交回复
热议问题