How to get next (or previous) enum value in C#

后端 未结 24 1990
深忆病人
深忆病人 2020-12-04 10:59

I have an enum which is defined like this:

public enum eRat { A = 0, B=3, C=5, D=8 };

So given value eRat.B, I want to get the

24条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 11:28

    Are you locked into using an enum by something that you have no control over?

    If you're not, I'd suggest using an alternative, probably Dictionary rat;

    If you create a Dictionary and you populate it with your data, enumerating over it is somewhat simpler. Also, it's a clearer mapping of intent-- you're mapping numbers to strings with this enum and you're trying to leverage that mapping.

    If you must use the enum, I'd suggest something else:

    var rats = new List() {eRat.A, eRat.B, eRat.C, eRat.D};
    

    As long as you're adding the values in-order and you keep it in sync, you greatly simplify the act of retrieving the next eRat.

提交回复
热议问题