您的位置:首页 > Web前端

Effective C#阅读笔记-5对于值类型保证0是一个有效状态

2011-08-07 11:25 267 查看
对于值类型默认没有赋值的情况下,默认值都是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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: