【问题标题】:What's the C# equivalent to the With statement in VB? [duplicate]VB 中与 With 语句等效的 C# 是什么? [复制]
【发布时间】:2009-07-24 01:08:01
【问题描述】:

可能重复:
Equivalence of “With…End With” in c#?

我非常喜欢 VB 的一个特性……With 声明。 C# 有什么等价物吗?我知道您可以使用using 不必键入名称空间,但仅限于此。在 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;

【问题讨论】:

标签: c# vb.net


【解决方案1】:

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

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

或在 C# 3.0 及更高版本中:

    var bar = new FooType
    {
        Name = "Bob Dylan",
        Age = 68,
        Location = "On Tour",
        IsCool = True
    };

    Stuff.Elements.Foo = bar;

【讨论】:

  • 您将“Stuff.Elements.Foo”视为一种类型。这是它在 VB 代码中的使用方式,还是实际上是对嵌套变量的引用?该技术完全有效,但我认为您的代码不太正确。
  • 前段时间我写了一篇blog,介绍了如何使用扩展方法和 lambda 表达式在 c# 中模拟 with 语句。
  • @Kenneth:这很聪明,尽管有人认为Object.Child.Grandchild.GreatGrandchild.Property1 = 1; 违反了得墨忒耳定律。
  • @Robert, 也许 但这是另一个主题的主题。
  • 这个答案的秒部分无效,Stuff.Elements.Foo 是一个变量。如果它是一种类型 - 那么你就错过了new
【解决方案2】:

除了对象初始值设定项(仅在构造函数调用中可用)之外,您能得到的最好的方法是:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 您将“Stuff.Elements.Foo”视为一种类型。这是它在 VB 代码中的使用方式,还是实际上是对嵌套变量的引用?该技术完全有效,但我认为您的代码不太正确。 (我在这里复制了夸克的评论,因为它也适用于这个答案)
    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 2012-12-01
    • 2010-11-27
    • 2012-07-13
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多