Effective C#阅读笔记-8Prefer Variable Initializers to Assignment Statements

当有很多构造函数的时候,要保证变量的初始化值相同,最好的办法就是使用初始化器语法,保证每一个构造函数的变量同步。初始化器语法将会由编译器生成代码,将会在基类的构造函数和此类的构造函数之前执行,执行的顺利跟类中变量定义的顺序相同。下面是一个初始化器的例子:

calss MyClass
{
       private int  _ins = 20;
       private int _str = "jedi";
}

Initializers are more than a convenient shortcut for statements in a constructor body. The statements generated by initializers are placed in object code before the body of your constructors. Initializers execute before the base class constructor for your type executes, and they are executed in the order the variables are declared in your class.

1.默认的系统初始化时会把所有的变量都初始化为0(low level using the CPU instructions初始化),所以如果初始化器语法只是把值初始化为0(只是多余的再次使用指令初始化),就没有必要使用初始化起语法,这样只会造成性能上的损失很浪费。

The system-generated 0 initialization is done at a very low level using the CPU instructions to set the entire block of memory to 0. Any extra 0 initialization on your part is superfluous. The C# compiler dutifully adds the extra instructions to set memory to 0 again. It's not wrongit's just inefficient. In fact, when value types are involved, it's very inefficient.

2.当需要为同一个对象,使用不同参数的初始化器的时候,不建议使用初始化器语法,构造器中再次初始化变量,这样会造成之前初始化器语法创建的对象生成的对象很快的变为垃圾对象,这样是一个浪费。

public class MyClass
{
  // declare the collection, and initialize it.
  private ArrayList _coll = new ArrayList( );

  MyClass( )
  {
  }

  MyClass( int size )
  {
    _coll = new ArrayList( size );
  }
}

The second inefficiency comes when you create multiple initializations for the same object. You should use the initializer syntax only for variables that receive the same initialization in all constructors.

3.初始化器语法不支持异常处理,如果需要在初始化的时候对异常进行处理需要在构造函数中初始化

Variable initializers are the simplest way to ensure that the member variables in your type are initialized regardless of which constructor is called. The initializers are executed before each constructor you make for your type. Using this syntax means that you cannot forget to add the proper initialization when you add new constructors for a future release. Use initializers when all constructors create the member variable the same way; it's simpler to read and easier to maintain.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值