用 Attribute 來定義有個好處,未來在增減 Enum 時可以一起進行修改,不用擔心會有遺漏而沒修改的問題。
- void Main()
- {
- PortAreaCode.F1Front.GetFloor().Dump(); /* F1 */
- }
- public enum PortAreaCode
- {
- [AreaMeta("None", 0)]
- None,
- [AreaMeta("F1", 1)]
- F1Front,
- [AreaMeta("F2", 1)]
- F2Front,
- }
- /// <summary>PortAreaCode 額外附屬資訊定義的 Attribute</summary>
- [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
- class AreaMetaAttribute : Attribute
- {
- public string Floor { get; private set; }
- public int WarehouseId { get; private set; }
- public AreaMetaAttribute() : this("None", 0) { }
- public AreaMetaAttribute(string floor, int warehouseId)
- {
- Floor = floor;
- WarehouseId = warehouseId;
- }
- }
- /// <summary>PortAreaCode 的擴充方法</summary>
- public static class PortAreaCodeExtensions
- {
- private static AreaMetaAttribute _defaultMeta = new AreaMetaAttribute();
- private static AreaMetaAttribute getMeta(PortAreaCode value)
- {
- FieldInfo field = typeof(PortAreaCode).GetField(value.ToString());
- if(field == null) { return _defaultMeta; }
- var meta = field.GetCustomAttribute<AreaMetaAttribute>();
- return meta ?? _defaultMeta;
- }
- public static string GetFloor(this PortAreaCode value)
- {
- return getMeta(value).Floor;
- }
- public static int GetWarehouseId(this PortAreaCode value)
- {
- return getMeta(value).WarehouseId;
- }
- }
0 回應:
張貼留言