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.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值