如果为 NULL,则分配默认值

Mar*_*hon 1 asp.net-mvc ef-code-first

我有一个 MVC 应用程序,用户可以在其中选择公司福利,有 10 种不同的福利,但他们最多不能拥有全部 10 种福利。在我看来,我列出了十个带有单选按钮的列表,以指示它们是否需要。控制器中还会执行计算,将所有值加在一起得出总计。

作为我的控制器中的示例 -

newuser.LifeAssurance.LifeAssuranceRequired = viewModel.LifeAssuranceRequired;    
newuser.LifeAssurance.LifeAssuranceSchemeName = viewModel.LifeAssuranceSchemeName;
newuser.LifeAssurance.LifeAssuranceProviderName = viewModel.LifeAssuranceProviderName;
newuser.LifeAssurance.LifeAssuranceBenefitLevel = viewModel.LifeAssuranceBenefitLevel;
newuser.LifeAssurance.LifeAssuranceEmployerCost = viewModel.LifeAssuranceEmployerCost;
newuser.LifeAssurance.LifeAssuranceEmployeeCost = viewModel.LifeAssuranceEmployeeCost;
Run Code Online (Sandbox Code Playgroud)

由于用户可能决定不选择此好处,如果他们没有在视图模型中做出选择,是否可以将成本分配为 0?我可以检查它是否为空并在这种情况下添加 0 吗?

Yoa*_*oav 5

您可以使用??运算符(请参阅此处),
如下所示:

string someString = null;
string someOtherString = someString ?? "0";
Run Code Online (Sandbox Code Playgroud)

如果 someString(或任何其他对象)不为 null,则使用它,否则使用运算符右侧的任何内容??