枚舉

2016-07-08 124 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 –