如何处理空值

问题描述 投票:0回答:1

我有以下 if 语句:

if (  (product.EmailType.Contains("cafe", StringComparison.OrdinalIgnoreCase)
    || product.EmailType.Contains("vendor", StringComparison.OrdinalIgnoreCase))
    && product.Supplier.Supplier_Type.Contains("Support"))
{
    //Do some stuff
}

基本上,如果 EmailType 包含特定值或不同的特定值,并且SupplierType 是Support,则执行某些操作。然而,Supplier_Type 为空的情况很常见。按照上面的方式,它会抛出异常。我如何解释它可能为空?如果它为空,它应该将整个 if 语句评估为 false 并继续。

我在最后一行尝试了空合并,但收到错误“Operator ??无法应用于类型 bool 和 bool”:

if (  (product.EmailType.Contains("cafe", StringComparison.OrdinalIgnoreCase)
    || product.EmailType.Contains("vendor", StringComparison.OrdinalIgnoreCase))
    && (product.Supplier.Supplier_Type.Contains("Support") ?? false))
{
    //Do some stuff
}

我还通过将最后一行写入如下来尝试空处理,但得到相同的错误:

&& product.Supplier.Supplier_Type?.Contains("Support")
c# .net linq
1个回答
0
投票

分解它

if (containsAny(product.EmailType, "cafe", "vendor") && containsAny(product.Supplier.Supplier_Type, "support"))
{
    //Do some stuff
}

bool containsAny(string? input, params string[] searchFor) =>
    input is not null && searchFor.Any(s => input.Contains(s, StringComparison.OrdinalIgnoreCase));
© www.soinside.com 2019 - 2024. All rights reserved.