为十进制铸造对象? (可空十进制) [英] Cast object to decimal? (nullable decimal)

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

问题描述

如果在setter方法​​有这样的:

If have this in the setter of a property:

decimal? temp = value as decimal?;

值=90

不过,中投后,温度是

But after the cast, temp is null...

什么是正确的方式做到这一点投?

What is the proper way to do this cast?

推荐答案

拆箱只有当该类型是相同的!你不能拆箱的对象不包含目标值。你需要的是沿

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;

这看起来值是否是可解析为一个十进制。如果是的话,然后将其分配给结果;否则分配。下面code的确大致相同,可能会更容易理解的人不熟悉的条件运算符

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天全站免登陆