C#;如何在递增时循环 Through/Wrap 枚举?

C#; How to Loop Through/Wrap Enumerations when Incremented?

假设你有一个字节值等于它的最大值,所以 byte aByte = 255;。当你增加一个值超过它的最大值时,它通常会回绕到它的最小值,所以如果我要写 Console.WriteLine(++aByte),这将打印 0 到控制台,因为它不能超过它的最大值值。

我希望在我创建的枚举中有同样的效果。所以假设这是代码:

using System;

namespace CSharp_Test_003
{
    class Program
    {
        static void Main()
        {
            Console.Title = "Enumerations";

            Season currentSeason = Season.Spring;
            Console.Write($"{currentSeason++} ");
            Console.Write($"{currentSeason++} ");
            Console.Write($"{currentSeason++} ");
            Console.Write($"{currentSeason++} ");
            Console.Write($"{currentSeason++} ");
        }

        private enum Season { Spring = 0, Summer, Autumn, Winter }
    }

目前打印出来:

Spring Summer Autumn Winter 4

但我真的很想在有“4”的地方说“Spring”。如果有一种实用的方法可以实现这一点,我真的很想知道。

您可以编写自己的以类似方式工作的自定义枚举

static void Main()
{
    Console.Title = "Enumerations";

    Season currentSeason = Season.Spring;
    Console.Write($"{currentSeason++} ");
    Console.Write($"{currentSeason++} ");
    Console.Write($"{currentSeason++} ");
    Console.Write($"{currentSeason++} ");
    Console.Write($"{currentSeason++} ");
}

//private enum Season { Spring = 0, Summer, Autumn, Winter }

public record Season
{
    public int Id { get; }
    public string Name { get; }
    private static readonly List<Season> _seasons = new();

    public static IReadOnlyList<Season> All => _seasons.OrderBy(x => x.Id).ToList();

    private Season(int id, string name)
    {
        Id = id;
        Name = name;
        _seasons.Add(this);
    }

    public static Season Spring { get; } = new Season(0, nameof(Spring));
    public static Season Summer { get; } = new Season(1, nameof(Summer));
    public static Season Winter { get; } = new Season(3, nameof(Winter));
    public static Season Autumn { get; } = new Season(2, nameof(Autumn));

    public override string ToString() => this.Name;

    public static implicit operator string(Season season) => season.ToString();

    public static Season operator ++(Season season)
    {
        if (season.Id == All.Count - 1)
            return All[0];

        return All[season.Id + 1];
    }
}