【发布时间】:2013-03-18 23:41:23
【问题描述】:
我的一个项目有一个值类型/结构,它表示视频格式的自定义标识符字符串。在这种情况下,它将包含一个内容类型字符串,但这可能会有所不同。
我使用了一个结构,因此它在传递时可以是强类型,并对初始字符串值执行一些健全性检查。
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");
将公共值公开为静态只读字段还是仅获取属性更好?如果我以后想更改它们怎么办?我看到整个 .Net 框架都使用了这两种方法,例如System.Drawing.Color 使用静态只读属性,而System.String 有一个用于String.Empty 的静态只读字段,System.Int32 有一个用于MinValue 的常量。
(大部分抄自this question,但有一个更具体且不直接相关的问题。)
【问题讨论】:
标签: c# constants object-model