gpt4 book ai didi

c# - "is not null here"

转载 作者:行者123 更新时间:2023-12-01 22:55:13 25 4
gpt4 key购买 nike

我有一个方法不断给我警告“这里不为空”。

        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;

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

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

最佳答案

此问题与您的 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;

}
}

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

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

该警告将消失。

关于c# - "is not null here",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73409464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com