什么是C#相当于VB中的With语句?

可能重复:
c#中“With … End With”的等价性?

我真的很喜欢VB的一个特性…… With语句。 C#有没有相应的东西? 我知道你可以使用use来不必输入命名空间,但仅限于此。 在VB中你可以这样做:

 With Stuff.Elements.Foo .Name = "Bob Dylan" .Age = 68 .Location = "On Tour" .IsCool = True End With 

C#中的相同代码是:

 Stuff.Elements.Foo.Name = "Bob Dylan"; Stuff.Elements.Foo.Age = 68; Stuff.Elements.Foo.Location = "On Tour"; Stuff.Elements.Foo.IsCool = true; 

不是,你必须分配一个变量。 所以

  var bar = Stuff.Elements.Foo; bar.Name = "Bob Dylan"; bar.Age = 68; bar.Location = "On Tour"; bar.IsCool = True; 

或者在C#3.0中:

  var bar = Stuff.Elements.Foo { Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = True }; 

除了对象初始化器(仅在构造函数调用中可用)之外,您可以获得的最佳结果是:

 var it = Stuff.Elements.Foo; it.Name = "Bob Dylan"; it.Age = 68; ... 

C#3.0中最接近的一点是,您可以使用构造函数初始化属性:

 Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}