“这里不为空”

Hob*_*eff 4 c# asp.net null visual-studio c#-4.0

我有一个方法不断地向我发出警告“此处不为空”。

        StockHolding stockHoldingFiltered = new StockHolding();
        List<StockHolding> stockHoldingsFiltered = new List<StockHolding>();
        IReadOnlyList<StockHolding> stockHoldings = this.GetAll();

        stockHoldingsFiltered = stockHoldings.Where(stckhold =>
            stckhold.PortfolioId.Equals(portfolioId) &&
            stckhold.StockSymbol.Equals(stockSymbol)).ToList();

        if(stockHoldingsFiltered != null)
            stockHoldingFiltered = stockHoldingsFiltered.FirstOrDefault();

        return stockHoldingFiltered;
Run Code Online (Sandbox Code Playgroud)

警告:“stockHoldingFiltered”此处不为空。CS8600:将 null 文字或可能的 null 值转换为不可为 null 的类型。

我无法让这个警告消失。有没有人遇到过这个问题并且能够解决这个警告?

小智 6

这个问题与你的 if 语句有关。您正在对 进行空检查ToList()。该列表不会为空,但也可以为空。下面是您的代码来演示这一点。

void Main()
{
    int portfolioId = 1;
    string stockSymbol = "USD";

    StockHolding stockHoldingFiltered = new StockHolding();
    List<StockHolding> stockHoldingsFiltered = new List<StockHolding>();
    IReadOnlyList<StockHolding> stockHoldings = StockHolding.GetAll();

    stockHoldingsFiltered = stockHoldings.Where(stckhold =>
        stckhold.PortfolioId.Equals(portfolioId) &&
        stckhold.StockSymbol.Equals(stockSymbol)).ToList();

    if (stockHoldingsFiltered != null) // this cannot be null as its returning a list. It might be empty but not null.
    {
        Console.WriteLine("I WASN't NULL, but has no records. Line below will fail.");
        //stockHoldingFiltered = stockHoldingsFiltered.FirstOrDefault();
    }
    
    if(stockHoldingsFiltered.Count > 0)
    {
        Console.WriteLine("I wasnt null but had 0 records. Line below is safe");
        stockHoldingFiltered = stockHoldingsFiltered.FirstOrDefault();
    }

    //return stockHoldingFiltered;
}

// You can define other methods, fields, classes and namespaces here
public class StockHolding
{
    public int PortfolioId { get; set; }
    public string StockSymbol { get; set; }
    
    public static IReadOnlyList<StockHolding> GetAll()
    {
        List<StockHolding> someList = new List<StockHolding>();
        
        return someList;
        
    }
}
Run Code Online (Sandbox Code Playgroud)

这输出:I WASN't NULL, but has no records. Line below will fail.

所以不要if (stockHoldingsFiltered != null)尝试使用if(stockHoldingsFiltered.Count > 0)

该警告将会消失。

  • 完全正确。它警告对实际上不为空的内容进行空检查。将 null 更改为“.Count”,它就会消失。 (2认同)