Cast object to decimal? (nullable decimal)

后端 未结 5 1136
天涯浪人
天涯浪人 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条回答
  •  囚心锁ツ
    2020-12-02 23:21

    Unboxing only works if the type is identical! You can't unbox an object that does not contain the target value. What you need is something along the lines of

    decimal tmpvalue;
    decimal? result = decimal.TryParse((string)value, out tmpvalue) ?
                      tmpvalue : (decimal?)null;
    

    This looks whether the value is parsable as a decimal. If yes, then assign it to result; else assign null. The following code does approximately the same and might be easier to understand for people not familiar with the conditional operator ?::

    decimal tmpvalue;
    decimal? result = null;
    if (decimal.TryParse((string)value, out tmpvalue))
        result = tmpvalue;
    

提交回复
热议问题