c#: assigning from nullable types

痞子三分冷 提交于 2021-02-16 13:46:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!