【问题标题】:Exposing common values from a custom structure/type从自定义结构/类型中公开常见值
【发布时间】: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


【解决方案1】:

属性是个好主意,除非您声明了从不更改的内容。

使用属性,您可以更改内部实现,而不会影响使用您的库和处理更改/变化的程序。消费程序不会中断,也不需要重新编译。

例如(我知道这是一个不好的例子,但你明白了..)

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;
    }
}

另外请记住,如果您决定将来将字段更改为属性,则会消耗代码中断。

【讨论】:

  • 在这种情况下,字段的工作方式与属性的工作方式相同,不是吗?
  • 如何将逻辑放入字段并根据该逻辑返回不同的结果?
  • 对不起,我更多地指的是值本身,允许您更改它。两者都可以更改(在设计时)并应用于任何调用者?
  • 是的,两者都可以更改 - 但将来您不能将字段转换为属性,而无需重新编译调用者。
猜你喜欢
  • 2011-10-25
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
相关资源
最近更新 更多