开发者

how do I create an extension method for a single specific enum

I've got an enum class full of command line switches for a third party app..I'm trying to make it so I can call on an item in the enum with a .ToSwitch (or whatever) so that I can make it validate the value type, spit out a formatted command-line switch with its parameter value. maybe I'm going about it wrong. After sitting here all day working on it (it's big) I'm finding it hard to let go and explore a different approach. lol any suggestions?

desired result:

Console.WriteLine(EnumClass.EnumItem.ToSwitch("optio开发者_开发技巧n"));

would spit out: -x "option"


For a specific enum:

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

Another way to do what you're talking about is with a Dictionary, which might be preferable. The keys would be the switch (or the enum value), and value would be the command format. Something like:

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

I suspect that would be more maintainable than defining an enum.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜