C#中,可空小数 [英] C#, Nullable decimal

查看:337
本文介绍了C#中,可空小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库,V1场可为空场。但我定义0(默认值),如果该值为null。

In my database, v1 field is nullable field. but I define 0 (default) if the value is null.

public decimal? v1 {
  get {
    return this._v1; 
  }
  set {
    this._v1 = value ?? 0M;
  }
}

所以现在,在V1不可为空变了。

so now, the v1 is not nullable variable anymore.

但我不能这样做,

decimal v2 = v1;

错误消息说,无法隐式转换类型'小数?为十进制。

在这种情况下,我必须转换为十进制,也是这样吗?

In this case, Do I have to convert to decimal, like this?

decimal v2 = Convert.ToDecimal(v1);

这很烦人的工作。和codeS是看起来很脏了。

It very annoying job. and codes are look dirty too.

任何人都知道更好的解决方案?请指点我。

Anyone know better solution? please advice me.

推荐答案

没有你不必在十进制转换?,您可以访问从基础值在可空键入如

No you don't have to convert the decimal?, you have access to the underlying value from the Nullable type e.g.

decimal v2 = v1.Value;

分配默认值设置为可空类型不让它不可为空的,它只是意味着它有一个值。可空类型有一个的HasValue 属性,它可以帮助你确定这一点。

Assigning a default value to a Nullable type does not make it non-nullable, it just means it has a value. Nullable types have a HasValue property which helps you determine this.

为了记录,我不会推荐的默认值 0 ,它可能会更有意义让它默认为考虑到它的可以的确实为空。如果您需要在您的应用程序的默认值,你可能会想使用 GetValueOrDefault 方法例如。

Just for the record, I wouldn't recommend defaulting the value to 0 it would probably make more sense letting it default to null considering it can indeed be null. If you need to have a default value in your app you will probably want to use the GetValueOrDefault method e.g.

decimal v2 = v1.GetValueOrDefault(0m);

这篇关于C#中,可空小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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