gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:16:20 25 4
gpt4 key购买 nike

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

我使用了一个结构,因此它在传递时可以是强类型的,并对初始字符串值执行一些健全性检查。实际的字符串值可以是任何东西并由外部插件库提供,因此数字 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
}

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

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

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

是否有更好的总体方法来执行此操作而不使用设计时指定的带有数值或纯字符串常量的 enum

最佳答案

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


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、任何枚举、其中任何一个的可为空值类型之一,或字符串。并且 case 标签中使用的常量必须是与管理类型兼容的编译时常量。

关于c# - 可与 switch() 一起使用的自定义结构/类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15488575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com