问题
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.
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");
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?
Is there a better overall method to do this without using a design time specified enum
with numeric values or plain string constants?
回答1:
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
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.
回答2:
Actually it might be better to refactor the code so that you don't have to use switch
statements at all. Although the construction itself is not an anti-pattern, but it is commonly accepted practice to use polymorphism instead. Here is another discussion of the ways to get rid of switch
.
回答3:
It seems to me that all the possible videoformats you're working with could be a classic example for using enumerations. I really don't see a problem to extend your enumeration with new values when some other formats will be added. Yes, the important thing we need to be sure that any VideoFormat
used in the program should fit the enumeration. But possibly it won't be a disadvantage.
来源:https://stackoverflow.com/questions/15488575/custom-structure-type-that-can-be-used-with-switch