如何在C#中获取下一个(或上一个)枚举值 [英] How to get next (or previous) enum value in C#

查看:741
本文介绍了如何在C#中获取下一个(或上一个)枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的枚举:

I have an enum which is defined like this:

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

因此给定值 eRat.B ,我想要得到下一个是 eRat.C

So given value eRat.B, I want to get the next one which is eRat.C

我看到的解决方案是(不进行范围检查)

The solution I see is (without range checking)

Array a = Enum.GetValues(typeof(eRat));
int i=0 ;
for (i = 0; i < a.GetLength(); i++)
{
       if (a.GetValue(i) == eRat.B)
            break;
}
return (eRat)a.GetValue(i+1):

现在,对于这么简单的事情来说,这太复杂了。您知道更好的解决方案吗?像 eRat.B + 1 Enum.Next(Erat.B)之类的东西?

Now that is too much complexity, for something that simple. Do you know any better solution?? Something like eRat.B+1 or Enum.Next(Erat.B)?

谢谢

推荐答案

感谢大家的回答和反馈。我惊讶地发现了这么多。查看它们并使用一些想法,我想到了最适合我的解决方案:

Thanks to everybody for your answers and feedback. I was surprised to get so many of them. Looking at them and using some of the ideas, I came up with this solution, which works best for me:

public static class Extensions
{

    public static T Next<T>(this T src) where T : struct
    {
        if (!typeof(T).IsEnum) throw new ArgumentException(String.Format("Argument {0} is not an Enum", typeof(T).FullName));

        T[] Arr = (T[])Enum.GetValues(src.GetType());
        int j = Array.IndexOf<T>(Arr, src) + 1;
        return (Arr.Length==j) ? Arr[0] : Arr[j];            
    }
}

这种方法的优点在于,它既简单又通用使用。作为通用扩展方法实现,您可以通过以下方式在任何枚举上调用它:

The beauty of this approach, that it is simple and universal to use. Implemented as generic extension method, you can call it on any enum this way:

return eRat.B.Next();

注意,我使用的是广义扩展方法,因此不需要在调用时指定类型,只是 .Next()

Notice, I am using generalized extension method, thus I don't need to specify type upon call, just .Next().

这篇关于如何在C#中获取下一个(或上一个)枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆