简体   繁体   English

仅当布尔值不为null时,才为布尔值分配不为null的值

[英]Assign non nullable value in boolean only if its non null

I have a object that has a boolean field called NameIndicator (External contract one). 我有一个对象,该对象具有一个名为NameIndicator的布尔字段(外部合同1)。 In my code, I made the my boolean "IsIndicated" as nullable. 在我的代码中,我将布尔值“ IsIndicated”设置为可为空。

How do I check for null and assign value only if non null? 如何检查null并仅在非null时才赋值?

I currently get compile time error with the below code as obvious its assining nullable to non nullable field 我目前收到以下代码的编译时错误,显然是将nullable设置为non nullable

 personDetails.Name= new Name_Format()
                    {
                        NameSpecified = true,
                        NameIndicator = contract.IsIndicated
                    };

If you want to assign a particular value in the case of null, and the value otherwise, you use the null coalescing operator . 如果要为null分配一个特定的值,否则要分配一个值,则可以使用null合并运算符

personDetails.Name= new Name_Format()
{
  NameSpecified = true,
  NameIndicator = contract.IsIndicated ?? true
};

That has the same semantics as 语义与

personDetails.Name = new Name_Format()
{
  NameSpecified = true,
  NameIndicator = contract.IsIndicated == null ? true : contract.IsIndicated.Value
};

except that of course it only calls IsIndicated once. 除了它当然只调用IsIndicated一次。

If you want the runtime to choose a default value for you then you can do 如果您希望运行时为您选择默认值,则可以

personDetails.Name = new Name_Format()
{
  NameSpecified = true,
  NameIndicator = contract.IsIndicated.GetValueOrDefault()
};

In this case it will choose "false", since that is the default value for Booleans. 在这种情况下,它将选择“ false”,因为这是布尔值的默认值。

If you want nothing at all to happen if the value is null then you can use an if statement: 如果您不希望任何值为null的事件,那么可以使用if语句:

if (contract.IsIndicated != null)
{
  personDetails.Name = new Name_Format()
  {
    NameSpecified = true,
    NameIndicator = contract.IsIndicated.Value
  }
};

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

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