有这个课程:
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);
解决此类问题的方法是,所涉及的类具有私有构造函数,并具有使用该实例的值初始化的公共静态字段/属性。这是具有固定数量的该类型的不可变实例的一种方法,同时仍然允许方法接受该类型的参数。
以下代码是有效的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 ");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句