枚举注入或代码更改?

时间:2013-06-27 07:00:32

标签: c# parsing .net-4.0 enums .net-4.5

我们的性别枚举类似于

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

允许用户输入'male''female'。一切都很好。 但明天,如果用户只需输入'm''f',则必须是'male''female'。 (通常,应支持简短格式'm''f'

无论如何,如果我在运行时修改 enum 或(任何 enum 注入内容),这可以实现吗?

目前,我只是使用

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

但是想知道是否有更好的方法可以做到这一点?而不是所有的if-else结构。

3 个答案:

答案 0 :(得分:1)

如果您的程序有某种UI,我建议不要触摸下划线数据结构,直到真的需要它。特别是如果你已经用这个开发了一个生产代码。

我建议您在UI层上接受“m”和“f”,就像增强您的应用功能,但在转换为“邮件”,“女性”之后。

通过这种方式,您将获得灵活性:如果有一天您想进行另一次更改(增强更多),只需更改“转换层”,所有工作都像以前一样。还要考虑多语言环境。

答案 1 :(得分:1)

您可以使用显示注释

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

答案 2 :(得分: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;


}

然后使用上面的方法检索数组中的值数组并比较用户输入。

编辑: 如果由于某种原因你无法访问枚举值,除了使用if ... else ...语句之外别无选择,只需确保根据可重用性要求将该登录封装在单独的函数或类中。 / p>

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;
....
}