仅当布尔值非空时才在布尔值中分配非空值
Assign non nullable value in boolean only if its non null
我有一个对象,它有一个名为 NameIndicator(外部合同一)的布尔字段。在我的代码中,我将我的布尔值 "IsIndicated" 设置为可为空。
如何检查 null 并仅在非 null 时才赋值?
我目前遇到以下代码的编译时错误,很明显它会将可空字段分配给不可空字段
personDetails.Name= new Name_Format()
{
NameSpecified = true,
NameIndicator = contract.IsIndicated
};
如果您想在 null 的情况下分配一个特定值,否则该值,您可以使用 null 合并运算符.
personDetails.Name= new Name_Format()
{
NameSpecified = true,
NameIndicator = contract.IsIndicated ?? true
};
与
具有相同的语义
personDetails.Name = new Name_Format()
{
NameSpecified = true,
NameIndicator = contract.IsIndicated == null ? true : contract.IsIndicated.Value
};
除了它当然只调用 IsIndicated
一次。
如果你想让运行时为你选择一个默认值,那么你可以这样做
personDetails.Name = new Name_Format()
{
NameSpecified = true,
NameIndicator = contract.IsIndicated.GetValueOrDefault()
};
在这种情况下,它将选择 "false",因为这是布尔值的默认值。
如果您不想在值为 null 时什么都不发生,那么您可以使用 if
语句:
if (contract.IsIndicated != null)
{
personDetails.Name = new Name_Format()
{
NameSpecified = true,
NameIndicator = contract.IsIndicated.Value
}
};
我有一个对象,它有一个名为 NameIndicator(外部合同一)的布尔字段。在我的代码中,我将我的布尔值 "IsIndicated" 设置为可为空。
如何检查 null 并仅在非 null 时才赋值?
我目前遇到以下代码的编译时错误,很明显它会将可空字段分配给不可空字段
personDetails.Name= new Name_Format()
{
NameSpecified = true,
NameIndicator = contract.IsIndicated
};
如果您想在 null 的情况下分配一个特定值,否则该值,您可以使用 null 合并运算符.
personDetails.Name= new Name_Format()
{
NameSpecified = true,
NameIndicator = contract.IsIndicated ?? true
};
与
具有相同的语义personDetails.Name = new Name_Format()
{
NameSpecified = true,
NameIndicator = contract.IsIndicated == null ? true : contract.IsIndicated.Value
};
除了它当然只调用 IsIndicated
一次。
如果你想让运行时为你选择一个默认值,那么你可以这样做
personDetails.Name = new Name_Format()
{
NameSpecified = true,
NameIndicator = contract.IsIndicated.GetValueOrDefault()
};
在这种情况下,它将选择 "false",因为这是布尔值的默认值。
如果您不想在值为 null 时什么都不发生,那么您可以使用 if
语句:
if (contract.IsIndicated != null)
{
personDetails.Name = new Name_Format()
{
NameSpecified = true,
NameIndicator = contract.IsIndicated.Value
}
};