C# 想知道是否有任何枚举类型仅在限制范围内重复其值

Lee*_*Lee 1 c# enums while-loop

对不起,我的愚蠢问题,我已经 7 年没有编程了,几乎忘记了一切。

我想做一个可以表达音符的系统,例如我创建了以下枚举,

public enum Notes { C = 0, D, E, F, G, A, B };
Notes N = Notes.C;

while (true)
{
    Console.WriteLine(N);
    N++;
}
Run Code Online (Sandbox Code Playgroud)

在这段代码中,一旦 Note 的 N 到达 Note.B,值就不会回到 C。如何强制值回到 Note.C?

你的回答对我很有帮助。

此致。

Swe*_*per 6

您可以使用余数运算符%将您的号码换回:

while (true)
{
    Console.WriteLine(N);
    N++;
    // you'd have to do some conversions here as N is not a numeric type
    N = (Notes)((int)N % 7);
}
Run Code Online (Sandbox Code Playgroud)

您也可以替换硬编码的幻数7

Enum.GetValues(typeof(Notes)).Length
Run Code Online (Sandbox Code Playgroud)

编辑:

我刚刚意识到您正在寻找一种可以实现这种环绕行为的类型。好吧,常规枚举无法做到这一点。您需要编写一个自定义struct,它本质上是int. 只是为了让您了解这会是什么样子:

struct Notes {
    private int intValue;
    private int IntValue {
        get => intValue;
        set {
            intValue = value % 7;
        }
    }

    private Notes(int intValue) {
        this.intValue = intValue;
    }

    public static Notes operator ++(Notes note) {
        Notes newNote = note;
        newNote.IntValue++;
        return newNote;
    }

    public static Notes operator --(Notes note) {
        Notes newNote = note;
        newNote.IntValue--;
        return newNote;
    }

    public static Notes C => new Notes(0);
    // all the other notes here...

    public override string ToString() => intValue switch {
        0 => "C",
        1 => "D",
        2 => "E",
        3 => "F",
        4 => "G",
        5 => "A",
        6 => "B",
        _ => intValue.ToString() // or throw an exception
    };
}
Run Code Online (Sandbox Code Playgroud)