繁体   English   中英

是否可以使用Enum with Pair Values,如字典

[英]Is it possible to use Enum with Pair Values like dictionary

在c#中我很难理解Enum。

在我的特定情况下,我需要以名称值格式存储常量值,如>

300秒= 5分钟

目前我使用这个课程。

  • 可以使用Enum代替,所以我对Enum类看起来很喜欢吗?
  • 我可以在Enum中存储一对值吗?

你能给我一个代码示例吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyWebSite.Models
{
    public class Reminders
    {
        private sortedDictionary<int, string> remindersValue = new SortedDictionary<int, string>();

        // We are settign the default values using the Costructor
        public Reminders()
        {
            remindersValue.Add(0, "None");
            remindersValue.Add(300, "5 minutes before");
            remindersValue.Add(900, "15 minutes before");
        }

        public SortedDictionary<int, string> GetValues()
        {
            return remindersValue;
        }

    }
}

您可以使用Tuple<int, int>作为字典键(至少使用.NET> = 4)。

但由于您实际上想要存储TimeSpan ,请将其用作密钥。

private static Dictionary<TimeSpan, string> TimeSpanText = new Dictionary<TimeSpan, string>();

static Reminders()
{
    TimeSpanText.Add(TimeSpan.Zero, "None");
    TimeSpanText.Add(TimeSpan.FromMinutes( 5 ), "5 minutes before");
    TimeSpanText.Add(TimeSpan.FromMinutes( 15 ), "15 minutes before");
    TimeSpanText.Add(TimeSpan.FromMinutes( 30 ), "30 minutes before");
    TimeSpanText.Add(TimeSpan.FromHours( 1 ), "1 hour before");
    // ....
}

public static string DisplayName(TimeSpan ts)
{
    string text;
    if (TimeSpanText.TryGetValue(ts, out text))
        return text;
    else
         throw new ArgumentException("Invalid Timespan", "ts");
}

您可以通过以下方式获得翻译:

var quarter = TimeSpan.FromMinutes(15);
string text = TimeSpanText[ quarter ];

您可以使用描述属性修饰枚举,然后通过反射访问它们。 例如,

enum ReminderTimes
{
    [Description("None")]
    None = 0,

    [Description("5 minutes before")]
    FiveMinutesBefore = 300,

    [Description("15 minutes before")]
    FifteenMinutesBefore = 900
}

您可以通过以下方式获取说明:

public static string GetDescription(this Enum value)
{            
    FieldInfo field = value.GetType().GetField(value.ToString());

    DescriptionAttribute attribute
            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
                as DescriptionAttribute;

    return attribute == null ? value.ToString() : attribute.Description;
}

另见: http//www.codeproject.com/Articles/13821/Adding-Descriptions-to-your-Enumerations

枚举实际上是一个命名的整数类型。 例如

public enum Foo : int 
{
   SomeValue = 100,
}

这意味着您创建了一个类型为'int'的Foo枚举和一些值。 我个人总是明确地说明发生了什么,但是c#隐式地使它成为'int'类型(32位int)。

您可以使用任何名称作为枚举名称,并可以使用Enum.IsDefined检查它是否是有效的枚举(例如,检查300是否是有效的枚举名称)。

更新

好吧,实际上,说实话,这并非100%正确。 此更新仅用于显示实际发生的情况。 枚举是一种值类型,其字段充当名称。 例如,上面的枚举实际上是:

public struct Foo 
{ 
    private int _value;
    public static Foo SomeValue { get { return new Foo() { _value = 100 }; } }
}

请注意,'int'是int的类型(在我的情况下是显式的)。 因为它是一个值类型,它具有与内存中的实数整数相同的结构 - 这可能是编译时编译器正在使用的内容。

如果你问你可以存储一个整数值对enum,那么你可以,例如

 public enum DurationSeconds
 {
     None = 0,
     FiveMinutesBefore = 300,
     FifteenMinutesBefore = 900,
     ThirtyMinutesBefore = 1800,
     OneHourBefore = 3600,
     TwoHoursBefore = 7200,
     OneDayBefore = 86400,
     TwoDaysBefore = 172800
 }

与我通常所做的相反,我将添加另一个答案,即IMO解决问题的答案。

在实际使用运行时检查之前,通常希望编译器尽可能多地进行检查。 这意味着在这种情况下使用Enum获取值:

// provides a strong type when using values in memory to make sure you don't enter incorrect values
public enum TimeSpanEnum : int
{
    Minutes30 = 30,
    Minutes60 = 60,
}

public class Reminders
{
    static Reminders()
    {
        names.Add(TimeSpanEnum.Minutes30, "30 minutes");
        names.Add(TimeSpanEnum.Minutes60, "60 minutes");
    }

    public Reminders(TimeSpanEnum ts)
    {
        if (!Enum.IsDefined(typeof(TimeSpanEnum), ts))
        {
            throw new Exception("Incorrect value given for time difference");
        }
    }

    private TimeSpanEnum value;
    private static Dictionary<TimeSpanEnum, string> names = new Dictionary<TimeSpanEnum, string>();

    public TimeSpan Difference { get { return TimeSpan.FromSeconds((int)value); } }
    public string Name { get { return names[value]; } }

}

在创建这样的程序时,该语言可以通过以下几种方式帮助您:

  • 您不能使用未定义的时间跨度
  • 它只对字典进行一次初始化,确切地说:构造类型时
  • Enum.IsDefined确保您不使用不正确的int值(例如,新的Reminders((TimeSpanEnum)5)将失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM