使用结构作为高级枚举类型并尝试按索引访问属性



我按照本指南为我的实现制作了一个更复杂的枚举类型。 http://www.huristic.co/blog/2018/1/30/c-advanced-enum-value-types

到目前为止一切顺利,但是现在我需要访问我理想地通过索引制作的结构属性。一个用例是,如果我进入整数列表,我希望能够提供带有季节的字符串列表,例如 {1,4,7} 会得到我 {"冬季"、"春季"、"夏季"} 例如。

因此,实际上,使用此示例,我希望能够选择索引为7的月份,并找出"夏季"的季节。

我的第一步是获得这样的名称:

IEnumerable<string> names = typeof(Month).GetProperties(BindingFlags.Static | BindingFlags.Public)
.Select(x => x.Name);

然后,我尝试使用以下命令获取特定的月份:

foreach(string name in names) { 
Month m = (Month) typeof(Month).GetType().GetProperties()
.Single(info => info.Name == name)
.GetValue(typeof(Month),null);
}

但是,这将导致我迭代整个集合以获取我想要获得的每个值。

最终,我认为我正朝着错误的方向前进,并且非常感谢一个指针。目前,我正在尝试在另一个类的方法中执行此操作,但不明白为什么它不能成为结构本身的getter,尽管考虑到正在使用的绑定属性,这可能很复杂。

如果您仍想在几个月中使用Enums,另一种方法是创建一个扩展类:

public enum Month
{
January = 1,
February = 2,
March = 3,
April = 4,
May = 5,
June = 6,
July = 7,
August = 8,
September = 9,
October = 10,
November = 11,
December = 12
}
public static class MonthExtensions
{
private static readonly Dictionary<int, string> _seasons = new Dictionary<int, string>
{
{1, "Spring" },
{2, "Summer" },
{3, "Autumn" },
{4, "Winter" }
};
private static readonly Dictionary<int, string> _names = new Dictionary<int, string>
{
{1,  "January"},
{2,  "February"},
{3,  "March"},
{4,  "April"},
{5,  "May"},
{6,  "June"},
{7,  "July"},
{8,  "August"},
{9,  "September"},
{10, "October"},
{11, "November"},
{12, "December"}
};
private static readonly Dictionary<int, int> _seasonMap = new Dictionary<int, int>
{
{1,  4},
{2,  4},
{3,  1},
{4,  1},
{5,  1},
{6,  2},
{7,  2},
{8,  2},
{9,  3},
{10, 3},
{11, 3},
{12, 4}
}; 
public static string GetSeason(int monthIndex)
=> ((Month)monthIndex).Season();
public static IEnumerable<string> GetSeasons(IEnumerable<int> monthIndexes)
=> monthIndexes.Select(i => GetSeason(i));
public static string Season(this Month month)
=> _seasons[_seasonMap[Index(month)]];
public static int Index(this Month month)
=> (int)month;
public static string Name(this Month month)
=> _names[Index(month)];
}

您可以使用静态字典将月份与其索引相关联:

public sealed class Month
{
private static Dictionary<short, Month> instances = new Dictionary<short, Month>();
private static Month AddInstance(string name, short index, string season)
{
instances[index] = new Month(name, index, season);
return instances[index];
}
public static IEnumerable<Month> GetByIndex(params short[] indices)
{
return indices.Select(i => instances[i]);
}
public static readonly Month January = AddInstance("January", 1, "Winter");
public static readonly Month February = AddInstance("February", 2, "Winter");
public static readonly Month March = AddInstance("March", 3, "Spring");
// ...
public string Name { get; private set; }
public short Index { get; private set; }
public string Season { get; private set; }
private Month(string name, short index, string season)
{
Name = name;
Index = index;
Season = season;
}
}

然后像这样使用:

Month.GetByIndex(1, 4, 7)
.Select(month => month.Season); // { "Winter", "Spring", "Summer" }

最新更新