可与switch()一起使用的自定义结构/类型 [英] Custom structure/type that can be used with switch()

查看:190
本文介绍了可与switch()一起使用的自定义结构/类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

One of my projects has a value type/struct that represents a custom identifier string for a video format. In this case, it's going to contain a content type string, but that can vary.

我使用了一个结构,因此可以在传递时对其进行强类型化,并对初始字符串值进行一些完整性检查. 实际的字符串值可以是任何值,并且可以由外部插件库提供,因此数字enum不适用.

I've used a struct so it can be strongly type when it's passed around, and perform some sanity checks on the initial string value. The actual string value could be anything and provided by external plugins libraries so a numeric enum doesn't apply.

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
}

由于存在一些非常常见的格式,因此我将它们公开为具有默认值的静态只读字段.

As there are a few very common formats, I've exposed these as static read only fields with default values.

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

这似乎在大多数情况下都有效,除了一个开关模块,在该开关模块中,该值必须为常数.我有什么方法可以直接在切换块中使用这种类型和静态值,而无需打开内部成员或.ToString()替代?

This seems to work on most cases except a switch block where it says the value has to be a constant. Is there any way I can make use of this type and the static values directly in a switch block without switching on the internal member or the .ToString() override?

有没有一种更好的整体方法来执行此操作而不使用指定的设计时间enum使用数字值或纯字符串常量?

Is there a better overall method to do this without using a design time specified enum with numeric values or plain string constants?

推荐答案

更新:由于C#7中关于switch语句的新规则,此答案不再完全准确.

UPDATE: This answer is no longer entirely accurate due to new rules for switch statements in C# 7. See the C# 7 documentation for details.

有什么方法可以直接在切换块中使用此类型和静态值

Is there any way I can make use of this type and the static values directly in a switch block

不. switch语句的管理类型必须是sbyte,byte,short,ushort,int,uint,long,ulong,char,bool,任何枚举,这些中的任何一个的可为空的值类型之一,或字符串.而且,案例标签中使用的常量必须是与管理类型兼容的编译时常量.

No. The governing type of a switch statement must be one of sbyte, byte, short, ushort, int, uint, long, ulong, char, bool, any enum, the nullable value types of any of those, or string. And the constants used in the case labels must be compile time constants compatible with the governing type.

这篇关于可与switch()一起使用的自定义结构/类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆