.NET3.0 对象初始化器

      开始用3.0的特性了,感觉很多东西都不是想象中的那么好用。当中最郁闷的当属用Linq的更新数据了,不过今天想说说对象初始化器,呵呵。
      其实对象初始化器一个比较大的作用就是减少了代码的书写数量,把一些原本应该人做的事情交给了框架。
      例如:我们有个Person类   

    public class Person
    
{
        
public string Name getset; }
        
public string ID getset; }

        
public Person()
        
{
        }

    }
2.0的代码:
            Person firstPerson = new Person();
            firstPerson.Name 
= "FirstPeron";
            firstPerson.ID 
= "1";
3.0的代码:
new Person{Name="FirstPerson",ID="1"},
3.0Reflector的代码:
      Person类的Name属性:
public string Name
{
    [CompilerGenerated]
    
get
    
{
        
return this.<Name>k__BackingField;
    }

    [CompilerGenerated]
    
set
    
{
        
this.<Name>k__BackingField = value;
    }

}

 
      实例化Person的代码:
    Person <>g__initLocal1 = new Person();
    
<>g__initLocal1.Name = "FirstPerson";
    
<>g__initLocal1.ID = "1";

 
我们可以看到实际的代码量并没有减少。
原文地址:https://www.cnblogs.com/jingtao/p/923893.html