Effective C#笔记(1)
条款1:使用属性代替可访问的数据成员
属性采用方法来实现,添加多线程支持就更加容易;
 1 public string Name
public string Name
2 {
{
3 get
  get
4 {
  {
5 lock(this)
    lock(this)
6 {
    {
7 return _name;
      return _name;
8 }
    }
9 }
  }
10 set
  set
11 {
  {
12 lock(this)
    lock(this)
13 {
    {
14 _name = value;
      _name = value;
15 }
    }
16 }
  }
17 }
}
虚属性,抽象属性,或者作为接口定义的一部分; public string Name
public string Name2
 {
{3
 get
  get4
 {
  {5
 lock(this)
    lock(this)6
 {
    {7
 return _name;
      return _name;8
 }
    }9
 }
  }10
 set
  set11
 {
  {12
 lock(this)
    lock(this)13
 {
    {14
 _name = value;
      _name = value;15
 }
    }16
 }
  }17
 }
} 1 public class Customer
public class Customer
2 {
{
3 private string _name;
  private string _name;
4 public Virtual string Name
  public Virtual string Name
5 {
  {
6 get{return _name;}
    get{return _name;}
7 set{_name = value;}
    set{_name = value;}
8 }
  }
9 
  
10 }
}
 public class Customer
public class Customer2
 {
{3
 private string _name;
  private string _name;4
 public Virtual string Name
  public Virtual string Name5
 {
  {6
 get{return _name;}
    get{return _name;}7
 set{_name = value;}
    set{_name = value;}8
 }
  }9
 
  
10
 }
}可以为一个属性的两个访问器提供不同的访问权限控制;
索引器:带参数的属性(parameterized property);
数据成员与属性在二进制上不兼容。
条款2:运行时常量(readonly)由于编译时常量(const)
编译时常量与运行时常量行为的不同表现为它们的访问方式。(编译时常量在编译后的代码中会被替换为常量值,而运行时常量会维持对readonly变量的引用)
条款3:操作符is或as优于强制转型
将参数向下转型为其它类型,或者是类,或者是接口。对于这种转型,尽可能选择as操作符。还有一种保险做法是先使用is来做一个转换测试,然后再使用as操作符;
as操作符比强制转型安全,而且有较好的效率,永远不会在转换过程中构造新的对象。
 1 object o = Factory.GetObject();
object o = Factory.GetObject();
2 MyType t = o as MyType;
MyType t = o as MyType;
3 if(t!=null)
if(t!=null)
4 {
{
5 //handle t
//handle t
6 }
}
7 else
else
8 {
{
9 //error
//error
10 }
}
 object o = Factory.GetObject();
object o = Factory.GetObject();2
 MyType t = o as MyType;
MyType t = o as MyType;3
 if(t!=null)
if(t!=null)4
 {
{5
 //handle t
//handle t6
 }
}7
 else
else8
 {
{9
 //error
//error10
 }
}
as操作不能应用于值类型(foreach循环语句中使用就是强制类型转换,因为他要保证值类型也能成功);
使用System.Object.GetType()方法可以获得对象的运行时确切类型,这种测试比is或as更严格,运行时测试主要应用于相等判断(参见条款9)。
 
                    
                
 
   
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号