2013-05-15 90 views
0

我有一個表單,可以從用戶收集數據。收集這些數據時,我會將其傳遞給各個合作伙伴,但每個合作伙伴都有自己的規則來處理每條數據,因此必須進行轉換。我可以做到這一點,但我擔心的是魯棒性。這裏有一些代碼:穩健地映射枚舉值

首先,我有一個枚舉。這被映射到下拉列表下拉列表 - 描述是文本值,並且int映射到該值。

public enum EmploymentStatusType 
{ 
    [Description("INVALID!")] 
    None = 0, 
    [Description("Permanent full-time")] 
    FullTime = 1, 
    [Description("Permanent part-time")] 
    PartTime = 2, 
    [Description("Self employed")] 
    SelfEmployed = 3 
} 

當表單提交時,所選擇的值被轉換爲它的正確的類型和存儲在另一個類 - 屬性看起來像這樣:

protected virtual EmploymentStatusType EmploymentStatus 
    { 
     get { return _application.EmploymentStatus; } 
    } 

對於線鋸的​​最終位的,我值轉換爲合作伙伴所需的字符串值:

Dictionary<EmploymentStatusType, string> _employmentStatusTypes; 
    Dictionary<EmploymentStatusType, string> EmploymentStatusTypes 
    { 
     get 
     { 
      if (_employmentStatusTypes.IsNull()) 
      { 
       _employmentStatusTypes = new Dictionary<EmploymentStatusType, string>() 
       { 
        { EmploymentStatusType.FullTime, "Full Time" }, 
        { EmploymentStatusType.PartTime, "Part Time" }, 
        { EmploymentStatusType.SelfEmployed, "Self Employed" } 
       }; 
      } 

      return _employmentStatusTypes; 
     } 
    } 

    string PartnerEmploymentStatus 
    { 
     get { return _employmentStatusTypes.GetValue(EmploymentStatus); } 
    } 

我打電話PartnerEmploymentStatus,然後返回最終輸出字符串。

任何想法如何使這可以變得更加健壯?

+3

什麼在您看來是「不穩健」? –

+0

我擔心的是,如果/當枚舉更改/增長 - 並且這是可能的,因爲新的合作伙伴可能有不同的規則需要調整,那麼所有其他類都包含需要更改和休息的映射。如果我有30個合作伙伴,這可能成爲一項重大任務。 – dotnetnoob

+1

然後,您需要將其重構爲一個翻譯區域。 Coudl就像訪問者模式實現一樣。你的選擇是分發代碼(如你現​​在所做的那樣)或訪問者來集中它。您需要建立一定程度的脆弱性,以便您的覆蓋測試在擴展時顯示問題,以便強制您正確地維護代碼。你處在一個相當普遍的困境中,這實際上是一個代碼組織問題。 –

回答

3

然後,您需要將其重構爲一個翻譯區域。可能會像訪問者模式實現一樣。你的選擇是分發代碼(如你現​​在所做的那樣)或訪問者來集中它。您需要建立一定程度的脆弱性,以便您的覆蓋測試在擴展時顯示問題,以便強制您正確地維護代碼。你是在一個相當普遍的窘境,這真的是一個組織代碼

1

我在我的一個項目中遇到過這樣的問題,我通過使用幫助函數和約定爲資源名稱解決了這個問題。

功能是這一個:

public static Dictionary<T, string> GetEnumNamesFromResources<T>(ResourceManager resourceManager, params T[] excludedItems) 
    { 
     Contract.Requires(resourceManager != null, "resourceManager is null."); 

     var dictionary = 
      resourceManager.GetResourceSet(culture: CultureInfo.CurrentUICulture, createIfNotExists: true, tryParents: true) 
      .Cast<DictionaryEntry>() 
      .Join(Enum.GetValues(typeof(T)).Cast<T>().Except(excludedItems), 
       de => de.Key.ToString(), 
       v => v.ToString(), 
       (de, v) => new 
       { 
        DictionaryEntry = de, 
        EnumValue = v 
       }) 
      .OrderBy(x => x.EnumValue) 
      .ToDictionary(x => x.EnumValue, x => x.DictionaryEntry.Value.ToString()); 
     return dictionary; 
    } 

的約定是,在我的資源文件,我將有一個是相同的枚舉值(在你的情況NonePartTime等)的性質。這是在助手功能中執行Join所需的,您可以根據需要進行調整。

所以,每當我想要一個枚舉值的(本地化)字符串描述我只要致電:

var dictionary = EnumUtils.GetEnumNamesFromResources<EmploymentStatusType>(ResourceFile.ResourceManager); 
var value = dictionary[EmploymentStatusType.Full];