Possible Duplicate:
Equivalence of “With…End With” in c#?可能重复:c#中“With ... End With”的等价性?
There was one feature of VB that I really like...the With
statement. Does C# have any equivalent to it? I know you can use using
to not have to type a namespace, but it is limited to just that. In VB you could do this:
我真的很喜欢VB的一个特性...... With语句。 C#有任何等价物吗?我知道您可以使用using来不必键入命名空间,但它仅限于此。在VB中你可以这样做:
With Stuff.Elements.Foo
.Name = "Bob Dylan"
.Age = 68
.Location = "On Tour"
.IsCool = True
End With
The same code in C# would be:
C#中的相同代码是:
Stuff.Elements.Foo.Name = "Bob Dylan";
Stuff.Elements.Foo.Age = 68;
Stuff.Elements.Foo.Location = "On Tour";
Stuff.Elements.Foo.IsCool = true;
3 个解决方案
#1
Not really, you have to assign a variable. So
不是,你必须分配一个变量。所以
var bar = Stuff.Elements.Foo;
bar.Name = "Bob Dylan";
bar.Age = 68;
bar.Location = "On Tour";
bar.IsCool = True;
Or in C# 3.0:
或者在C#3.0中:
var bar = Stuff.Elements.Foo
{
Name = "Bob Dylan",
Age = 68,
Location = "On Tour",
IsCool = True
};
#2
Aside from object initializers (usable only in constructor calls), the best you can get is:
除了对象初始化器(仅在构造函数调用中可用)之外,您可以获得的最佳结果是:
var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...
#3
The closest thing in C# 3.0, is that you can use a constructor to initialize properties:
C#3.0中最接近的是,您可以使用构造函数初始化属性:
Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}
#1
Not really, you have to assign a variable. So
不是,你必须分配一个变量。所以
var bar = Stuff.Elements.Foo;
bar.Name = "Bob Dylan";
bar.Age = 68;
bar.Location = "On Tour";
bar.IsCool = True;
Or in C# 3.0:
或者在C#3.0中:
var bar = Stuff.Elements.Foo
{
Name = "Bob Dylan",
Age = 68,
Location = "On Tour",
IsCool = True
};
#2
Aside from object initializers (usable only in constructor calls), the best you can get is:
除了对象初始化器(仅在构造函数调用中可用)之外,您可以获得的最佳结果是:
var it = Stuff.Elements.Foo;
it.Name = "Bob Dylan";
it.Age = 68;
...
#3
The closest thing in C# 3.0, is that you can use a constructor to initialize properties:
C#3.0中最接近的是,您可以使用构造函数初始化属性:
Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}