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

查看:35
本文介绍了如何在 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+1Enum.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天全站免登陆