可与switch()一起使用的自定义结构/类型

Dea*_*nna 8 c# value-type object-model switch-statement

我的一个项目有一个值类型/结构,表示视频格式的自定义标识符字符串.在这种情况下,它将包含一个内容类型字符串,但这可能会有所不同.

我已经使用了一个结构体,因此当它传递时它可以是强类型,并对初始字符串值执行一些健全性检查.实际的字符串值可以是任何内容,由外部插件库提供,因此数字enum不适用.

public struct VideoFormat {
    private string contentType;

    public VideoFormat(string contentType) {
        this.contentType = contentType;
    }

    public string ContentType {
        get { return this.contentType; }
    }

    public override string ToString() {
        return this.contentType;
    }

    // various static methods for implicit conversion to/from strings, and comparisons
}
Run Code Online (Sandbox Code Playgroud)

由于有一些非常常见的格式,我将这些格式暴露为具有默认值的静态只读字段.

public static readonly VideoFormat Unknown = new VideoFormat(string.Empty);
public static readonly VideoFormat JPEG = new VideoFormat("image/jpeg");
public static readonly VideoFormat H264 = new VideoFormat("video/h264");
Run Code Online (Sandbox Code Playgroud)

这似乎适用于大多数情况,除了一个开关块,它表示值必须是常量.有没有什么办法可以直接在开关块中使用这种类型和静态值而无需打开内部成员或.ToString()覆盖?

如果没有使用enum数值或普通字符串常量指定的设计时间,是否有更好的整体方法?

Eri*_*ert 11

更新:由于C#7中的switch语句的新规则,此答案不再完全准确.有关详细信息,请参阅C#7文档.


有什么办法可以直接在开关块中使用这种类型和静态值

否.switch语句的管理类型必须是sbyte,byte,short,ushort,int,uint,long,ulong,char,bool,any enum,其中任何一个的可空值类型或字符串.案例标签中使用的常量必须是与管理类型兼容的编译时常量.