从自定义结构/类型公开通用值 [英] Exposing common values from a custom structure/type
问题描述
我的一个项目的值类型/结构表示视频格式的自定义标识符字符串.在这种情况下,它将包含一个内容类型字符串,但是可以有所不同.
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.
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");
将公共值公开为静态只读字段还是仅获取属性更好?如果我以后要更改该怎么办?我看到整个.Net框架都使用了这两种方法,例如System.Drawing.Color
使用静态只读属性,而System.String
具有用于String.Empty
的静态只读字段,而System.Int32
具有用于MinValue
的const.
Is it better to expose the common values as static read only fields or as get only properties? what if I want to change them later? I see both methods used throughout the .Net framework, e.g. System.Drawing.Color
uses static readonly properties while System.String
has a static read only field for String.Empty
, and System.Int32
has a const for MinValue
.
(大部分复制自此问题,但包含更具体且不直接相关的问题.)
(Mostly copied from this question but with a more specific and not directly related question.)
推荐答案
除非您声明从不更改,否则属性是个好主意.
Properties are a good idea unless you are declaring something that never changes.
使用属性,您可以更改内部实现,而不会影响占用您库的程序并处理更改/变体.使用程序不会中断,也不需要重新编译.
With properties you can change the inside implementation without affecting programs consuming your library and handle changes / variations. Consuming programs wont break and wont require to be recompiled.
例如(我知道这是一个不好的例子,但您明白了.)
e.g. (I know this is a bad example but you get the idea..)
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;
}
}
还请记住,如果您以后决定将字段更改为属性,则会消耗大量代码.
Also keep in mind that if you decided to change a field to a property in the future, consuming code breaks.
这篇关于从自定义结构/类型公开通用值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!