有这个课程:
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);
答案 0 :(得分: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 ");
}