枚举

2016-07-08 125 views
0

有这个类:枚举

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

则:

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

的一点是,我想有这样的事情:

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

所以此方法的结果应为:

SET STB MEDIA CTRL type:tv action:play 

方法的调用将是:

SET_STB_MEDIA_CTRL (MultimediaConstants.TV, MultimediaConstants.ACTION_PLAY); 
+2

因为无法创建静态类的实例,所以无法请求将静态类的实例作为方法参数 – Sehnsucht

+1

这些arent枚举。这些是类。你可以使用'enum'关键字而不是class来创建枚举。那么你可以使用你想要的值。 –

+0

@Sehnsucht这就是为什么他想要'Enum of strings',就像java可以让你做 –

回答

3

接近的问题,像这是一个问题有一个私有构造函数的类,并且具有与值初始化的公共静态字段/属性的方式那个例子。这是一种固定有限数量的该类型不可变实例的方法,同时仍允许方法接受该类型的参数。

以下代码是有效的C#6.0。

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 "); 
} 
+0

不要忘记让他们只读! –

+0

@ DanielA.White,因为它们是只有getter的属性,所以它们是自动只读的 – GreatAndPowerfulOz

+0

啊没有注意到这是c#6 –