枚举注入或代码更改

本文关键字:代码 注入 枚举 | 更新日期: 2023-09-27 18:20:01

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

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

并且允许用户输入CCD_ 1或CCD_。一切都很好。但明天,如果用户只输入'm''f',则必须是'male''female'。(通常,应支持缩写形式'm''f'

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

现在,我只使用

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

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

枚举注入或代码更改

我强烈建议使用一组固定的选项而不是自由文本将用户输入转换为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。。。其他的语句只需确保根据可重用性要求将登录封装在一个单独的函数或类中。

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

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

我建议用户界面层也接受"m"answers"f",就像增强你的应用程序功能一样,但在t转换为"mail"、"female"之后。

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

您可以使用显示注释

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