【问题标题】:Enum of strings in C# [duplicate]C#中的字符串枚举[重复]
【发布时间】:2016-07-08 20:10:18
【问题描述】:

有这个类:

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);

【问题讨论】:

  • 你不能要求静态类的实例作为方法参数,因为你不能创建静态类的实例
  • 这些不是枚举。这些是类。您可以使用enum 关键字而不是类来创建枚举。然后你可以使用你想要的值。
  • @Sehnsucht 这就是为什么他想要Enum of strings,就像 java 让你做的那样
  • @SamIam 我明白了;我只是解释了为什么这是不可能的
  • @RichardBarker 它们在概念上是枚举。在一般 CS 意义上,这是对该术语的适当使用。然而,C# 的枚举实现无法做到这一点。这使得这些不是 C# 枚举,但在一般意义上称它们为枚举仍然适用。

标签: c# enums


【解决方案1】:

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

以下代码在 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 ");
}

【讨论】:

  • 别忘了将它们设为只读!
  • @DanielA.White,因为它们是 getter-only 属性,所以它们是自动只读的
  • 啊没注意到这是c# 6
  • @Servy 谢谢,完美!
猜你喜欢
  • 2011-09-11
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多