c# - 库存检查器代码不起作用,它有一个错误并且无法编译
问题描述
我正在尝试将此代码作为一个有趣的项目运行。我遇到了一个错误。任何人都可以帮我运行这个吗?
错误在这一行:
_httpClient ??= new HttpClient
编译器中的错误:
mcs -out:main.exe main.cs main.cs(45,30): error CS1525: Unexpected symbol `=' Compilation failed: 1 error(s), 0 warnings compiler exit status 1
谁能帮我解决这个问题?
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Timers;
using HtmlAgilityPack;
using Timer = System.Timers.Timer;
namespace Ps5Watcher
{
public class Program
{
[ThreadStatic] private static HttpClient _httpClient;
private static readonly Random Rng = new Random();
private static readonly Dictionary<string, Func<HtmlDocument, bool>> SiteRules =
new Dictionary<string, Func<HtmlDocument, bool>>
{
{
"https://www.walmart.com/ip/Sony-PlayStation-5-Digital-Edition/493824815",
doc => !doc.DocumentNode.Descendants("div")
.Any(node =>
node.HasClass("prod-blitz-copy-message") && node.InnerText.Contains("out of
stock"))
}
};
private static void Main(string[] args)
{
var checkInterval = new Timer(1000);
checkInterval.Elapsed += CheckSites;
checkInterval.Start();
while (!Console.ReadLine()?.Equals("stop", StringComparison.InvariantCultureIgnoreCase) ??
true)
{
}
}
private static void CheckSites(object sender, ElapsedEventArgs e)
{
foreach (var site in SiteRules)
{
_httpClient ??= new HttpClient
{
DefaultRequestHeaders =
{{"User-Agent", "Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101
Firefox/78.0"}}
};
Thread.Sleep(Rng.Next(50, 2000));
// load the html document
var doc = new HtmlDocument();
doc.Load(_httpClient.GetStreamAsync(site.Key).GetAwaiter().GetResult());
// check our rule for this site and report the results
var host = new Uri(site.Key).Host;
if (site.Value(doc))
{
Console.WriteLine($"{DateTimeOffset.UtcNow:s} ({host}) - Available!");
// open the page immediately
Process.Start(site.Key);
// stop the timer so that we don't keep opening the page
((Timer)sender).Stop();
}
else
{
Console.WriteLine($"{DateTimeOffset.UtcNow:s} ({host}) - Not in stock");
}
}
}
}
}
解决方案
从 C# 8.0 开始可以使用空合并赋值。您可以将其替换为
if (_httpClient == null) _httpClient = new HttpClient...
推荐阅读
- python - 如何加快熊猫字符串功能?
- javascript - 如何从另一个文件中提取动态href链接
- docker - pod 创建卡在 ContainerCreating 状态
- angular - Angular:子路由刷新问题
- amazon-web-services - 将数据库和数据仓库迁移到 AWS
- php - Yii2中如何实现join查询
- c# - 当我们使用 OpenXMLPowerTools 创建单个幻灯片的演示文稿时图标丢失
- javascript - Java 脚本 - 导出和导入
- java - 将字符映射到国际键集的键码
- .net - AWS Lambda 上带有 netcoreapp2.0 的 Npgsql 无法连接(有超时) - 我该如何解决?