2013-05-15 92 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];