65.9K
CodeProject 正在变化。 阅读更多。
Home

对象和集合初始化

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (3投票s)

2010年12月7日

CPOL

1分钟阅读

viewsIcon

25820

对象和集合初始化

什么是对象初始化? 对象初始化是 C# 3.0 中的一项新特性,它允许创建对象而无需编写过多的冗长代码,也无需显式调用构造函数。例如
class Employee
{
  public string Name { get; set; }
  public string Address { get; set; }

 public Employee(){}
 public Employee (string name) { Name= name;  }
}
如果不使用对象初始化来定义对象,那么你的代码会是这样:
Employee emp = new Employee();
emp.Name="pranay";
emp.Address = "Ahmedabad";
Employee emp = new Employee("Krunal");
emp.Address = "Ahmedabad";
在 ILDASM 中的 IL 代码
// Code size       32 (0x20)
  .maxstack  2
  .locals init ([0] class anonymoustype.Employee emp)
  IL_0000:  nop
  IL_0001:  newobj     instance void anonymoustype.Employee::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  ldstr      "pranay"
  IL_000d:  callvirt   instance void anonymoustype.Employee::set_Name(string)
  IL_0012:  nop
  IL_0013:  ldloc.0
  IL_0014:  ldstr      "Ahmedabad"
  IL_0019:  callvirt   instance void anonymoustype.Employee::set_Address(string)
  IL_001e:  nop
  IL_001f:  ret
但是使用对象初始化,代码会是这样:
Employee emp = new Employee{ Name="Pranay", Address="Ahmedabad"  };
Employee emp = new Employee() { Name="Pranay", Address="Ahmedabad"  };
Employee emp = new Employee("Hemang") { Address="Ahmedabad"  };
重要的是,以上所有代码行都创建了 Employee 对象。但第一行创建 Object 而没有显式调用构造函数,而是调用了无参数构造函数,而另外两行则显式调用了各自的构造函数。第一条语句在 ILDASM 中的 IL 代码是:
.entrypoint
  // Code size       34 (0x22)
  .maxstack  2
  .locals init ([0] class anonymoustype.Employee emp,
           [1] class anonymoustype.Employee '<>g__initLocal0')
  IL_0000:  nop
  IL_0001:  newobj     instance void anonymoustype.Employee::.ctor()
  IL_0006:  stloc.1
  IL_0007:  ldloc.1
  IL_0008:  ldstr      "Pranay"
  IL_000d:  callvirt   instance void anonymoustype.Employee::set_Name(string)
  IL_0012:  nop
  IL_0013:  ldloc.1
  IL_0014:  ldstr      "Ahmedabad"
  IL_0019:  callvirt   instance void anonymoustype.Employee::set_Address(string)
  IL_001e:  nop
  IL_001f:  ldloc.1
  IL_0020:  stloc
正如你所看到的,对象初始化代码与上面的 IL 代码类似。但关键在于,无参数构造函数是由编译器生成的,而我没有在第一条语句中编写。为什么对象初始化是 C# 3.0 的一部分? 再次说明,这项新特性是 C# 3.0 为了支持 LINQ 而加入的。你可以在 这里 看到匿名类型与此特性的结合使用。集合初始化 集合初始化允许使用对象初始化特性来创建对象集合。例如
List<Employee> emp = new List<Employee>
      {
        new Employee { Name="Pranay", Address="Ahmedabad"  },
        new Employee { Name="Krunal", Address="Mevada"  },
        null
     };
总结 对象初始化允许用一行代码(即一个表达式)创建对象。因此,我们可以创建大量的对象集合,而无需编写过多的冗长代码,这在集合初始化中可以体现。
© . All rights reserved.