Getting the max value of an enum

后端 未结 11 2292
旧时难觅i
旧时难觅i 2020-12-07 13:42

How do you get the max value of an enum?

11条回答
  •  北海茫月
    2020-12-07 13:57

    It is not usable in all circumstances, but I often define the max value myself:

    enum Values {
      one,
      two,
      tree,
      End,
    }
    
    for (Values i = 0; i < Values.End; i++) {
      Console.WriteLine(i);
    }
    
    var random = new Random();
    Console.WriteLine(random.Next((int)Values.End));
    

    Of course this won't work when you use custom values in an enum, but often it can be an easy solution.

提交回复
热议问题