2013-06-27 50 views
1

我們有一個性別枚舉枚舉注入或代碼更改?

enum Gender 
{ 
    female=0, 
    male=1, 
} 

和用戶被允許進入任何'male''female'。一切都很好。 但明天如果用戶只是輸入'm''f'它必須是'male''female'。 (一般情況下,短期形式'm''f'應該得到支持)

反正是有,如果我修改枚舉或(任何枚舉在運行時注射的東西)可以做到這一點?

現在,我只是用

string value = GetUserInput(); 
if (userEnteredValue == 'm') 
{ 
    value = "male"; 
} 
else if (userEnteredValue == 'f') 
{ 
    value = "female"; 
} 
//else enum.tryparse(stuff) 

,但不知道是否有這樣做的任何更好的方式?而不是所有的if-else結構。

+0

你可以使用StartWith對嗎?或者像輸入中的自動完成/搜索功能 – arifnpm

+0

@arifnpm:爲什麼我應該使用StartWith?找到沒有理由去做 –

+1

也許你可以在擴展方法中實現自定義分析邏輯? http://kirillosenkov.blogspot.com/2007/09/making-c-enums-more-usable-parse-method.html – Arie

回答

1

我強烈建議您使用的選項組固定的,而不是自由文本用戶輸入轉換爲0/1。

但是如果您必須有一種可能性是使用自定義屬性。 所以它看起來會是這樣的:

enum Gender 
{ 

    [Synonyms("f","female","FL")] 
    female=0, 
    [Synonyms("m","male","ML")] 
    male=1, 
} 

屬性看起來應該是這樣的:

public sealed class Synonyms: Attribute 
{ 
    private readonly string[] values; 

    public AbbreviationAttribute(params string[] i_Values) 
    { 
     this.values = i_Values; 
    } 

    public string Values 
    { 
     get { return this.values; } 
    } 
} 

然後使用一個通用的方法來檢索您的可能的同義詞

public static R GetAttributeValue<T, R>(IConvertible @enum) 
{ 
    R attributeValue = default(R); 

    if (@enum != null) 
    { 
     FieldInfo fi = @enum.GetType().GetField(@enum.ToString()); 

     if (fi != null) 
     { 
      T[] attributes = fi.GetCustomAttributes(typeof(T), false) as T[]; 

      if (attributes != null && attributes.Length > 0) 
      { 
       IAttribute<R> attribute = attributes[0] as IAttribute<R>; 

       if (attribute != null) 
       { 
        attributeValue = attribute.Value; 
       } 
      } 
     } 
    } 

    return attributeValue; 


} 

然後使用上面的方法檢索數組中的值數組並比較用戶輸入。

編輯: 如果前面一些原因,你必須枚舉值進不去,就沒有其他的選擇,如果...否則,而不是使用...語句只是一定要封裝了登錄界面,在一個單獨的功能或類別根據可重用性要求。

public eGender getEnumFrom UserInput(string i_userInput) 
{ 
    if(i_userInput == "male") then return eGender.male; 
    if(i_userInput == "m") then return eGender.male; 
    if(i_userInput == "ML") then return eGender.male; 
.... 
} 
+0

謝謝..但只是出於好奇。當我無法修改枚舉時會發生什麼?可能在枚舉序列化的情況下,或者當我指的是第三方提供的枚舉? –

+0

如果是這種情況,您除了使用IF ELSE之外別無選擇,只要確保將其封裝在一個單一的方法中。我會發佈一個示例 – Mortalus

+0

謝謝mort –

1

如果你的程序有某種用戶界面,我建議不要觸摸下劃線數據結構,直到你真的需要。特別是如果你已經用這個開發了一個生產代碼。

我會建議你的UI層接受「m」和「f」,就像你的應用程序功能的增強,但後轉換爲「郵件」,「女性」。

通過這種方式,您將獲得靈活性:如果有一天您想進行其他更改(增強更多),只需更改「轉換層」和所有像以前一樣的作品。也想想多語言環境。

+0

不幸的是,這個輸入是從PDF文件中獲得的,所以我不能在UI層 –

+1

@nowhewhomustnotbenamed中做:但是你可以創建「轉換層」,它接受任何支持格式的數據並以固體數據層格式轉換它。反之亦然。 – Tigran

1

您可以使用顯示註解

enum Gender 
{ 
    [Display(Name="f")] 
    female=0, 
    [Display(Name="m")] 
    male=1, 
} 
+0

顯示註釋?我會檢查出..有趣的感謝 –