首页 > 解决方案 > 库存检查器代码不起作用,它有一个错误并且无法编译

问题描述

我正在尝试将此代码作为一个有趣的项目运行。我遇到了一个错误。任何人都可以帮我运行这个吗?

错误在这一行:

_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#

解决方案


从 C# 8.0 开始可以使用空合并赋值。您可以将其替换为

if (_httpClient == null) _httpClient = new HttpClient...

推荐阅读