简体   繁体   English

c#:从可空类型中分配

[英]c#: assigning from nullable types

如果我有一个可以为空的“十进制?d”并且我想将d分配给不可为空的e,那么正确的方法是什么?

decimal e = d ?? 0.0;
decimal e;
if(d.HasValue) 
{
    e = d.Value;
}

You need to determine whether you even can, ie whether the nullable d has a value or not. 你需要确定你是否可以,即可空的d是否有值。

if (d.HasValue) { e = d.Value; } else { /* now what */ }

Another interesting case comes up quite commonly where you want to assign to a nullable using a ternary, in which case you have to cast to make both branches have the same type. 另一个有趣的案例出现在你想要使用三元组分配给可空的地方,在这种情况下你必须进行强制转换以使两个分支具有相同的类型。

d = foo ? 45 : (int?)null;

Note the case of null to (int?) so that both branches have the same type. 注意null to(int?)的情​​况,以便两个分支具有相同的类型。

decimal e;

if (d.HasValue)
{
    e = d.Value;
}

I usually go with something like this: 我通常会这样做:

decimal e = d.HasValue ? d.Value : decimal.Zero;

The reason here is that I'm a fan of ternary operations and I usually assign the value I would get if I had perfermed a failed TryParse() for the type I am dealing with. 这里的原因是我是三元操作的粉丝,我通常会分配我得到的值,如果我已经为我正在处理的类型执行了失败的TryParse() For decimal that would be decimal.Zero , for int it would be 0 as well. 对于decimaldecimal.Zero ,对于int它也是0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM