与 VB 中的 With 语句等效的 C# 是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/1175334/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the C# equivalent to the With statement in VB?
提问by Bob Dylan
Possible Duplicate:
Equivalence of “With…End With” in c#?
可能的重复:
C# 中“With…End With”的等价物?
There was one feature of VB that I really like...the Withstatement. Does C# have any equivalent to it? I know you can use usingto not have to type a namespace, but it is limited to just that. In VB you could do this:
我非常喜欢 VB 的一项功能……With声明。C# 有什么等价的吗?我知道您可以使用usingto 不必键入名称空间,但仅限于此。在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;
采纳答案by Robert Harvey
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
    };
回答by foson
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}
回答by Pavel Minaev
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;
...

