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

Gib*_*boK 6 .net c#

在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;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 8

您可以使用Tuple<int, int>as作为字典键(至少使用.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");
}
Run Code Online (Sandbox Code Playgroud)

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

var quarter = TimeSpan.FromMinutes(15);
string text = TimeSpanText[ quarter ];
Run Code Online (Sandbox Code Playgroud)

  • TimeSpan.FromSeconds和TimeSpan.FromMinutes等而不是ctor提供了有关imo正在发生的事情的更好描述. (4认同)

lc.*_*lc. 5

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

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

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

    [Description("15 minutes before")]
    FifteenMinutesBefore = 900
}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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