一个或下一个枚举 [英] Next or previous enum

查看:175
本文介绍了一个或下一个枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于已赋值的枚举,是什么让一个给定值,下一首或上枚举的最佳方式。例如,考虑此枚举:

 公共枚举TimeframeType {
无= 0,
[简介( 1月)]
现在= 30,
[说明(1-3个月)]
短= 90,
[说明(3-6个月 )]
培养基= 180,
[说明(6个月以上)]
长= 360
}

有没有一种很好的方式创建一个会做EnumPrevious(TimeframeType.Short)函数返回TimeframeType.Now和EnumNext(TimeframeType.Short)将返回TimeframeType.Medium <? / p>

我已经写了一个丑陋的实施EnumNext的,但我不相信它是这样做的最佳方式。 。我希望别人已经解决了这个问题。



 公共静态牛逼EnumNext< T>(T值),其中T:结构{
T [] =值(T [])Enum.GetValues(typeof运算(T));

INT I;
为(i = 0; I< values.Length;我++){
如果(的Object.Equals(值,值[I])){
中断;
}
}
如果(I> = values.Length - 1){
返回值[values.Length - 1];
}其他{
返回值[I + 1];
}
}


解决方案

您正在试图解决错误的问题。这是太复杂了一个简单枚举来计算。重构枚举类和使用比较接口。



如果你看一下这是如何的可能的被类实现这条路线是开放的:

 公共类时限:IComparable的
{
私人诠释天;

公众诠释天
{

{
天=价值;
}
}

公众诠释的CompareTo(对象除外)
{
//看到这个实施 - http://msdn.microsoft。 COM / EN-US /库/ system.icomparable.aspx#Mtps_DropDownFilterText
}


公共字符串描述
{
获取代码,以返回说明串,即1-3个月
}

}


Given an enum that has assigned values, what is the best way to get the next or previous enum given a value. For example, consider this enum:

public enum TimeframeType {
    None = 0,
    [Description("1 month")]
    Now = 30,
    [Description("1-3 months")]
    Short = 90,
    [Description("3-6 months")]
    Medium = 180,
    [Description("6+ months")]
    Long = 360
}

Is there a good way create a function that would do EnumPrevious(TimeframeType.Short) returns TimeframeType.Now and EnumNext(TimeframeType.Short) would return TimeframeType.Medium?

I already wrote an ugly implementation of EnumNext but I'm not convinced that it is the best way to do so. I'm hoping someone else has already tackled this problem.

public static T EnumNext<T>(T value) where T : struct {
    T[] values = (T[])Enum.GetValues(typeof(T));

    int i;
    for (i = 0; i < values.Length; i++) {
        if (object.Equals(value, values[i])) {
            break;
        }
    }
    if (i >= values.Length - 1) {
        return values[values.Length - 1];
    } else {
        return values[i + 1];
    }
}

解决方案

You are trying to solve the wrong problem. This is far too complex for a simple enum to calculate. Refactor the enum to a class and use a comparison interface.

If this route is open to you look at how this could be implemented by a class:

public class TimeFrame: IComparable
{
   private int days;

   public int Days
   {
        set 
        {
             days = value;
        }
   }

   public int CompareTo(object other)
   {
        //see this for implementation -- http://msdn.microsoft.com/en-us/library/system.icomparable.aspx#Mtps_DropDownFilterText
   }


   public string Description
   {
       get code to return the description string , ie "1-3 months"
   }

}

这篇关于一个或下一个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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