简体   繁体   中英

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.

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.

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. For decimal that would be decimal.Zero , for int it would be 0 as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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