C#中"With ... End With"的等价性?

odi*_*seh 19 c# vb.net with-statement

我知道C#有using关键字,但会using自动处理对象.

With...End WithVisual Basic 6.0中是否存在等价?

tom*_*ing 34

它不等同,但这种语法对你有用吗?

Animal a = new Animal()
{
    SpeciesName = "Lion",
    IsHairy = true,
    NumberOfLegs = 4
};
Run Code Online (Sandbox Code Playgroud)

  • "With"不会创建实例,所以这是错误的. (4认同)

Phi*_*ert 32

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

  • 这是真的.但是如果你有一个类的方法返回'this',那么你可以将方法链接在一起. (4认同)

exp*_*boy 17

没有等价物,但我认为讨论语法可能很有趣!

我相当喜欢;

NameSpace.MyObject.
{
    active = true;
    bgcol = Color.Red;
}
Run Code Online (Sandbox Code Playgroud)

还有其他建议吗?

我无法想象添加这种语言功能会很困难,基本上只是预处理.

编辑:

我厌倦了等待这个功能,所以这里和扩展实现了类似的行为.

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

用法;

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

编辑:有趣的是,似乎有人用这个"解决方案"再次打败了我.那好吧..


sup*_*cat 8

我认为相当于以下VB:

With SomeObjectExpression()
  .SomeProperty = 5
  .SomeOtherProperty = "Hello"
End With
Run Code Online (Sandbox Code Playgroud)

这将是C#:

{
  Var q=SomeOtherExpression();
  q.SomeProperty = 5;
  q.SomeOtherProperty = "Hello";
}
Run Code Online (Sandbox Code Playgroud)

唯一真正的区别在于,在vb中,标识符没有名称"q",而只是在遇到句点而没有任何其他标识符之前使用的默认标识符.

  • 外括号设置变量q的范围.如果对象表达式是类而不是结构,我认为上面的VB.Net和C#代码几乎完全等价.前一个语句是如何使用with语句的示例,后一个语句是C#转换.C#示例使用了几个setter,因为这是任意选择的VB.net示例.关键点在于"with"等同于定义临时变量,然后在使用没有前面标识符的句点时使用它. (2认同)

Jos*_*eph 6

没有相当于With ... End With in C#.

这是一个比较图表,说明了Visual Basic和C#之间的差异.