代码之家  ›  专栏  ›  技术社区  ›  odiseh

C#中“With…End With”的等价性?[副本]

  •  29
  • odiseh  · 技术社区  · 16 年前

    using 自动处理该对象。

    With...End With Visual Basic 6.0 ?

    6 回复  |  直到 11 年前
        1
  •  38
  •   tomfanning    16 年前

    Animal a = new Animal()
    {
        SpeciesName = "Lion",
        IsHairy = true,
        NumberOfLegs = 4
    };
    
        2
  •  35
  •   Philippe Leybaert    16 年前

    C#没有相应的语言结构。

        3
  •  22
  •   expelledboy    13 年前

    NameSpace.MyObject.
    {
        active = true;
        bgcol = Color.Red;
    }
    

    还有其他建议吗?

    我无法想象添加这个语言功能会很困难,本质上只是一个预处理。

    /// <summary>
    /// C# implementation of Visual Basics With statement
    /// </summary>
    public static void With<T>(this T _object, Action<T> _action)
    {
        _action(_object);
    }
    

    LongInstanceOfPersonVariableName.With(x => {
         x.AgeIntVar = 21;
         x.NameStrVar = "John";
         x.NameStrVar += " Smith";
         //etc..
    });
    

    有趣的是,似乎有人再次用这个“解决方案”打败了我。好吧。。

        4
  •  10
  •   KyleMit Steven Vachon    11 年前

    With SomeObjectExpression()
      .SomeProperty = 5
      .SomeOtherProperty = "Hello"
    End With
    

    这会是 C :

    {
      Var q=SomeOtherExpression();
      q.SomeProperty = 5;
      q.SomeOtherProperty = "Hello";
    }
    

    唯一真正的区别是,在vb中,标识符没有名称“q”,而只是遇到句点时使用的默认标识符,前面没有任何其他标识符。

        5
  •  7
  •   Peter Mortensen Pieter Jan Bonestroo    11 年前

    C#

    这是 a comparison chart 这说明了Visual Basic和C#之间的区别。

        6
  •  3
  •   Peter Mortensen Pieter Jan Bonestroo    11 年前

    VB.NET 功能。

    推荐文章