相关: 从枚举属性中获取枚举
我想要绑定枚举的最可维护的方式,并且它将本地化字符串值关联到某些东西。
如果我将枚举和类放在同一个文件中,我会觉得有点安全,但我必须假设有更好的方法。我也考虑过让枚举名称与资源字符串名称相同,但恐怕我不能总是在这里强制执行。
using CR = AcmeCorp.Properties.Resources;
public enum SourceFilterOption
{
LastNumberOccurences,
LastNumberWeeks,
DateRange
// if you add to this you must update FilterOptions.GetString
}
public class FilterOptions
{
public Dictionary<SourceFilterOption, String> GetEnumWithResourceString()
{
var dict = new Dictionary<SourceFilterOption, String>();
foreach (SourceFilterOption filter in Enum.GetValues(typeof(SourceFilterOption)))
{
dict.Add(filter, GetString(filter));
}
return dict;
}
public String GetString(SourceFilterOption option)
{
switch (option)
{
case SourceFilterOption.LastNumberOccurences:
return CR.LAST_NUMBER_OF_OCCURANCES;
case SourceFilterOption.LastNumberWeeks:
return CR.LAST_NUMBER_OF_WEEKS;
case SourceFilterOption.DateRange:
default:
return CR.DATE_RANGE;
}
}
}