1

我们有一个类似的性别枚举

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

并且用户可以输入'male''female'。一切都很好。但是明天如果用户只是输入'm'or'f'它必须是'male'or 'female'。(一般来说,短格式'm'还是'f'应该支持的)

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

现在,我只是使用

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

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

4

3 回答 3

1

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

我建议您在 UI 层上也接受“m”和“f”,就像增强您的应用程序功能一样,但在转换为“mail”、“female”之后。

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

于 2013-06-27T07:05:53.927 回答
1

您可以使用显示注释

enum Gender
{
  [Display(Name="f")]
  female=0,
  [Display(Name="m")]
  male=1,
}
于 2013-06-27T07:12:40.397 回答
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... 语句之外别无选择,请确保根据可重用性要求将该登录封装在单独的函数或类中.

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;
....
}
于 2013-06-27T07:13:12.803 回答