将对象转换为十进制?(可为空的十进制) [英] Cast object to decimal? (nullable decimal)

查看:27
本文介绍了将对象转换为十进制?(可为空的十进制)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在属性的 setter 中有这个:

If have this in the setter of a property:

decimal? temp = value as decimal?;

值 = "90"

但是在转换之后,temp 是 null...

But after the cast, temp is null...

进行此演员表的正确方法是什么?

What is the proper way to do this cast?

推荐答案

取消装箱仅在类型相同时才有效!您不能对不包含目标值的 object 拆箱.你需要的是类似

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;

这会查看该值是否可解析为 decimal.如果是,则将其分配给result;否则分配 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;

这篇关于将对象转换为十进制?(可为空的十进制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆