在c#中我很难理解Enum.
在我的特定情况下,我需要以名称值格式存储常量值,如>
300秒= 5分钟
目前我使用这个课程.
你能给我一个代码示例吗?
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)
您可以使用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)
您可以使用描述属性修饰枚举,然后通过反射访问它们.例如,
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
| 归档时间: |
|
| 查看次数: |
6139 次 |
| 最近记录: |