Is there a try Convert.ToInt32… avoiding exceptions

前端 未结 7 1903
长发绾君心
长发绾君心 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:16

    Return a nullable int. that way you know whether you parsed 0.

    int? value = int.TryParse(stringValue, out int outValue) 
        ? outValue
        : default(int?);
    

提交回复
热议问题