【问题标题】:how do I create an extension method for a single specific enum如何为单个特定枚举创建扩展方法
【发布时间】:2011-04-29 23:35:14
【问题描述】:

我有一个枚举类,其中包含第三方应用程序的命令行开关。我正在努力做到这一点,以便我可以使用 .ToSwitch (或其他)调用枚举中的一个项目,以便我可以让它验证值类型,用它的参数值吐出一个格式化的命令行开关。也许我做错了。在坐了一整天之后(它很大),我发现很难放手去探索不同的方法。大声笑有什么建议吗?

想要的结果:

Console.WriteLine(EnumClass.EnumItem.ToSwitch("option"));

会吐出:-x "option"

【问题讨论】:

    标签: c# enums extension-methods


    【解决方案1】:

    对于特定的枚举:

    public enum MyEnum
    {
        value1 = 1,
        value2 = 2,
    }
    
    public static class EnumExtensions
    {
        public static string ToSwitch(this MyEnum val, string option)
        {
            switch (val)
            {
                case MyEnum.value1 : return "x " + option;
                case MyEnum.value2 : return "y " + option;
                default: return "error";
            }
        }
    }
    

    您所说的另一种方法是使用Dictionary,这可能更可取。键是开关(或枚举值),值是命令格式。比如:

    Dictionary<string, string> CmdFormats = new Dictionary<string, string>()
    {
        { "-a", "filename" },
        { "-n", "number" }
    };
    

    我怀疑这比定义枚举更易于维护。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-19
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      相关资源
      最近更新 更多