我的一个项目有一个值类型/结构,表示视频格式的自定义标识符字符串。在本例中,它将包含内容类型字符串,但这可能会有所不同。
我使用了一个结构体,因此它在传递时可以是强类型的,并对初始字符串值执行一些健全性检查。
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
, and System.Int32
有一个常量MinValue
.
(大部分是复制自这个问题 https://stackoverflow.com/q/15488575/588306但有一个更具体且不直接相关的问题。)
属性是个好主意,除非你声明的东西never变化。
通过属性,您可以更改内部实现,而不会影响使用您的库的程序并处理更改/变化。使用程序不会中断,也不需要重新编译。
例如(我知道这是一个不好的例子,但你明白了..)
public static VideoFormat H264Format
{
get{
// This if statement can be added in the future without breaking other programs.
if(SupportsNewerFormat)
return VideoFormat.H265;
return VideoFormat.H264;
}
}
另请记住,如果您决定将来将字段更改为属性,则消耗代码会中断。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)