gpt4 book ai didi

c# - 为什么我的异步程序抛出 NullReferenceException

转载 作者:行者123 更新时间:2023-12-02 20:25:54 28 4
gpt4 key购买 nike

我收到以下异常:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at GoogleProducts.Program.<Main>d__0.MoveNext() in C:\Code\test\GoogleProducts\Program.cs:line 60
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at GoogleProducts.Program.<Main>(String[] args)

来源是:

private static async Task Main(string[] args)
{
var queries = new[]
{
"seico watch",
"citizen watch",
"orient watch",
"bulova watch",
"seagull watch",
"glashuette watch"
};

var client = new WebClient();

foreach (var query in queries)
{
var url = @"https://www.google.co.uk/search?tbm=shop&q=" + query;
var content = await client.DownloadStringTaskAsync(url);

var doc = new HtmlDocument();
doc.LoadHtml(content);

var linkedProducts = doc.DocumentNode.Descendants("a")
.Select(a => a.GetAttributeValue("href", null))
.Where(href => href.StartsWith(@"/shopping/product/"));

var productTasks = linkedProducts.Select(async linkedProduct =>
{
var productUrl = @"https://www.google.co.uk" + linkedProduct;

var productPage = await client.DownloadStringTaskAsync(productUrl);
var productDoc = new HtmlDocument();
productDoc.LoadHtml(productPage);

var productName = productDoc.DocumentNode.Descendants("title").FirstOrDefault()?.InnerText;

var sellersNodes = productDoc.DocumentNode.Descendants("tr")
.Where(tr => tr.GetAttributeValue("class", null) == "os-row");

var sellers = sellersNodes.Select(seller => new Seller
{
Name = seller.Descendants("a").First().InnerText,
Price = decimal.Parse(seller.Descendants("td").Last().InnerText.Substring(2))
}).ToArray();

return sellers.Any() ? new Product(sellers, productName) : null;
}).Where(product => product != null);

foreach (var productTask in productTasks)
{
var product = await productTask;
var result =
$"{product.Name}{Environment.NewLine}Best price: {product.BestPrice()}, from {product.BestPriceSellers()}"
+ $", Average price: {product.AveragePrice()}";

Console.WriteLine(result + Environment.NewLine);
}
}
}

如果没有更多详细信息,无法发布。

最佳答案

您正在执行).Where(product => product != null);Task<Product> 的列表中,不是 Product .

因此,即使 Product 为空,Task<Product>不是。

为了更好地查看它,请指定类型:

 .Where((Task<Product> product) => product != null);

这应该可以编译并显示错误的命名如何欺骗您。

关于c# - 为什么我的异步程序抛出 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49987360/

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