2010-05-18 93 views
1

我有反映枚舉(DictionaryType)選項的Guid非常直接的方式代碼C#反射枚舉選項恆定值

if (dictionaryType == DictionaryType.RegionType) 
    return Consts.DictionaryTypeId.RegionType; 

if (dictionaryType == DictionaryType.Nationality) 
    return Consts.DictionaryTypeId.Nationality; 

請給我建議最好的方式,以反映枚舉選項靜態只讀guid值。

預先感謝您

編輯了一下後: 我不能指定任何屬性枚舉選項,「因爲枚舉是在數據模型組件聲明和枚舉不應該與執行相結合(的GUID,表...)

回答

1

除了喬恩的回答,您可以提供的GUID作爲一個單獨的類的字段,其中字段具有相同的名稱及其相應的枚舉值。

這可以用於填充字典快速查找後:

using System; 
using System.Collections.Generic; 

namespace SO2856896 
{ 
    enum DictionaryType 
    { 
     RegionType, 
     Nationality 
    } 

    class Consts 
    { 
     public class DictionaryTypeId 
     { 
      public static Guid RegionType = new Guid("21EC2020-3AEA-1069-A2DD-08002B30309D"); 
      public static Guid Nationality = new Guid("21EC2020-3AEA-1069-A2DD-08002B30309E"); 
     } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      Dictionary<DictionaryType, Guid> table = new Dictionary<DictionaryType, Guid>(); 

      Type idType = typeof(Consts.DictionaryTypeId); 
      foreach (DictionaryType dicType in Enum.GetValues(
       typeof(DictionaryType))) 
      { 
       System.Reflection.FieldInfo field = idType 
        .GetField(dicType.ToString(), 
         System.Reflection.BindingFlags.Static 
         | System.Reflection.BindingFlags.Public); 
       Guid guid = (Guid)field.GetValue(null); 
       table[dicType] = guid; 
      } 

      foreach (DictionaryType dicType in Enum.GetValues(
       typeof(DictionaryType))) 
      { 
       Console.Out.WriteLine(dicType + ": " + table[dicType]); 
      } 
     } 
    } 
} 

輸出:

RegionType: 21ec2020-3aea-1069-a2dd-08002b30309d 
Nationality: 21ec2020-3aea-1069-a2dd-08002b30309e 

我不完全知道我會選擇我自己,但也許一個的組合喬恩的回答是一本字典,用來查看上面的指導和反思來填充它。

+0

是的,Id屬性是一個不錯的主意,但我不能將它分配給枚舉選項:( 枚舉是在數據模型庫中,不應該與實現(Guids)結合 – 2010-05-18 11:59:16

+0

更改代碼以反映單獨的類 – 2010-05-18 12:08:16

+0

謝謝你你的時間和精力! – 2010-05-18 12:28:47

1

一些簡單的選擇:

  • switch語句
  • Dictionary<DictionaryType, Guid>(其中可以通過反射來填充,如果你真的想)
+0

你喜歡什麼樣的代碼:切換15個以上的反射情況? – 2010-05-18 11:54:51

+0

@Andrew:我不確定,老實說......可能是Lasse的裝飾枚舉本身的方式,除非你需要在其他地方提供GUID。 – 2010-05-18 12:00:04