2011-09-12 31 views
0

,因爲我不能在枚舉空間,我試圖做這樣的事情,但似乎不喜歡它....枚舉與空間屬性下拉列表

public enum EnumState 
{ 
    NewYork, 
    NewMexico 
} 


public EnumState State 
    { 
     get 
     { 
      return EnumState ; 
     } 
     set 
     { 
      if (EnumState .ToString() == "NewYork".ToString()) 
      { 
       value = "New York".ToString(); 
       EnumState = value; 
      } 
     } 
    } 
+2

'if(EnumState == EnumState.NewYork)' – SLaks

+3

在setter中設置'value'的值是個壞主意。 –

+0

你爲什麼要在字符串上調用'.ToString()'?你打算通過給一個枚舉類型變量賦值一個字符串值來完成什麼?無論你想要做什麼,都可能有更好的方法來處理它。 – recursive

回答

3

我看到這個一般處理通過在枚舉成員上添加[StringValue("New York")]屬性。快速谷歌搜索返回this blog post,這是一個很好的做法。

基本上使屬性類:

public class StringValueAttribute : Attribute { 

    public string StringValue { get; protected set; } 

    public StringValueAttribute(string value) { 
     this.StringValue = value; 
    } 
} 

和擴展的方法來訪問它:

public static string GetStringValue(this Enum value) { 
     // Get the type 
     Type type = value.GetType(); 

     // Get fieldinfo for this type 
     FieldInfo fieldInfo = type.GetField(value.ToString()); 

     // Get the stringvalue attributes 
     StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
      typeof(StringValueAttribute), false) as StringValueAttribute[]; 

     // Return the first if there was a match, or enum value if no match 
     return attribs.Length > 0 ? attribs[0].StringValue : value.ToString(); 
    } 

那麼你的枚舉應該是這樣的:

public enum EnumState{ 
    [StringValue("New York")] 
    NewYork, 
    [StringValue("New Mexico")] 
    NewMexico, 
} 

,你可以只需使用myState.GetStringValue();

+0

如果你需要確切的字符串模擬爲什麼只是不要調用EnumState.NewYork.ToString()? – sll

+1

@sll - 因爲「紐約」有空間。 '紐約'不。 –

+0

對此的更好改進是使用現有的DisplayNameAttribute並擴展它。 –

1

您可以使用此模式:C# String enums

它將允許您爲枚舉中的每個枚舉定義一個自定義字符串名稱。