Cast object to decimal? (nullable decimal)

后端 未结 5 1104
天涯浪人
天涯浪人 2020-12-02 22:54

If have this in the setter of a property:

decimal? temp = value as decimal?;

value = \"90\"

But after the cast, temp is nul

5条回答
  •  萌比男神i
    2020-12-02 23:15

    you should parse the decimal. But if you want your decimal to be null when the string is not correct, use TryParse :

    decimal parsedValue;
    decimal? temp = decimal.TryParse(value, out parsedValue)
                    ? value
                    : (decimal?)null;
    

    This way you will avoid exceptions while parsing ill formated strings.

    Almost all primitive types provide a Parse and TryParse methods to convert from string.

    Is is also recommended to pass a culture for the provider argument to the method to avoid problems with the decimal separator. If you're reading from another system, CultureInfo.InvariantCulture is probably the way to go (but it's not the default).

    bool TryParse(string s, NumberStyles style,
      IFormatProvider provider, out decimal result)
    

提交回复
热议问题