C#中字符串的枚举

Enum of strings in C#

本问题已经有最佳答案,请猛点这里访问。

请上这门课:

1
2
3
4
5
6
7
8
9
public static class Command
{
    public const string SET_STB_MEDIA_CTRL ="SET STB MEDIA CTRL";
    public static string ECHO ="ECHO";
    public static string SET_CHANNEL ="SET CHANNEL";
    public static string GET_VOLUMN ="GET VOLUMN";
    public static string GET_MAX_VOLUMN ="GET MAX VOLUMN";
    public string SET_STB_MEDIA_LIST ="SET STB MEDIA LIST";
}

然后:

1
2
3
4
5
6
7
8
9
10
public static class MultimediaConstants
{
    public const string VIDEO ="video";
    public const string AUDIO ="audio";
    public const string PHOTO ="photo";
    public const string ALL ="all";
    public const string BACKGROUND_MUSIC ="background_music";
    public const string TV ="tv";
    public const string ACTION_PLAY ="play";
}

关键是,我想要这样的东西:

1
2
3
4
public static string SET_STB_MEDIA_CTRL (MultimediaConstants type,  MultimediaConstants action)
{
    return Command.SET_STB_MEDIA_CTRL +"type:" + type +"action:" + action;
}

所以这个方法的结果应该是:

1
 SET STB MEDIA CTRL type:tv action:play

方法的调用将是:

1
 SET_STB_MEDIA_CTRL (MultimediaConstants.TV, MultimediaConstants.ACTION_PLAY);


处理此类问题的方法是让所讨论的类有一个私有的构造函数,并让用该实例的值初始化的公共静态字段/属性。这是一种拥有固定数量的该类型不可变实例的方法,同时仍然允许方法接受该类型的参数。

以下代码是有效的C 6.0。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Command
{
    private Command(string value)
    {
        Value = value;
    }

    public string Value { get; private set; }

    public static Command SET_STB_MEDIA_CTRL { get; } = new Command("SET STB MEDIA CTRL");
    public static Command ECHO { get; } = new Command("ECHO");
    public static Command SET_CHANNEL { get; } = new Command("SET CHANNEL");
    public static Command GET_VOLUMN { get; } = new Command("GET VOLUMN");
    public static Command GET_MAX_VOLUMN { get; } = new Command("GET MAX VOLUMN");
    public static Command SET_STB_MEDIA_LIST { get; } = new Command("SET STB MEDIA LIST");
}