问题
If I have a nullable "decimal? d" and I want to assign d to non nullable e, what is the proper way?
回答1:
decimal e = d ?? 0.0;
回答2:
decimal e;
if(d.HasValue)
{
e = d.Value;
}
回答3:
You need to determine whether you even can, i.e. 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.
回答4:
decimal e;
if (d.HasValue)
{
e = d.Value;
}
回答5:
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.
来源:https://stackoverflow.com/questions/810015/c-assigning-from-nullable-types