天天看點

Effective C#閱讀筆記-5對于值類型保證0是一個有效狀态

對于值類型預設沒有指派的情況下,預設值都是0。

枚舉類型,繼承于System.ValueType,預設值情況下枚舉是從0開始的,但是可以修改

public enum Planet
{
  // Explicitly assign values.
  // Default starts at 0 otherwise.
  Mercury = 1,
  Venus = 2,
  Earth = 3,
  Mars = 4,
  Jupiter = 5,
  Saturn = 6,
  Neptune = 7,
  Uranus = 8,
  Pluto = 9
}

Planet sphere = new Planet();
      

如果不是使用顯示的指定枚舉,用new配置設定一個枚舉對象,sphere 目前的值類型預設值為0,此時sphere不再是一個有效的狀态 ,其他引用的地方将會可能出錯!可以使用下面的方法解決這個問題,為0指定一個為初始化的值

public enum Planet
{
  None = 0,
  Mercury = 1,
  Venus = 2,
  Earth = 3,
  Mars = 4,
  Jupiter = 5,
  Saturn = 6,
  Neptune = 7,
  Uranus = 8,
  Pluto = 9
}

Planet sphere = new Planet();
      

另外對于使用了Flags位标志屬性的枚舉,切記一定需要設定None值為0,確定0是一個有效的狀态并且表示:“the absence of all flags”

[Flags]
public enum Styles
{
  None = 0,
  Flat = 1,
  Sunken = 2,
  Raised = 4,
}
      
字元串預設值為null,可以通過屬性來對外公開字元串的通路,通過get做檢查,如果為null傳回String.Empty字元串,類型内部檢查。
public struct LogMessage
{
  private int _ErrLevel;
  private string _msg;

  public string Message
  {
    get
    {
      return (_msg != null ) ?
        _msg : string.Empty;
    }
    set
    {
      _msg = value;
    }
  }
}
      

You should use this property inside your own type. Doing so localizes the null reference check to one location. The Message accessor is almost certainly inlined as well, when called from inside your assembly. You'll get efficient code and minimize errors.

The system initializes all instances of value typess to 0. There is no way to prevent users from creating instances of value types that are all 0s. If possible, make the all 0 case the natural default. As a special case, enums used as flags should ensure that 0 is the absence of all flags.

繼續閱讀