Equivalence of “With…End With” in C#? [duplicate]

2019-01-06 22:58发布

This question already has an answer here:

I know that C# has the using keyword, but using disposes of the object automatically.

Is there the equivalence of With...End With in Visual Basic 6.0?

6条回答
我想做一个坏孩纸
2楼-- · 2019-01-06 23:32

C# doesn't have an equivalent language construct for that.

查看更多
一夜七次
3楼-- · 2019-01-06 23:35

There is no equivalent structure in C#. This is a Visual Basic 6.0 / VB.NET feature.

查看更多
Bombasti
4楼-- · 2019-01-06 23:40

There's no equivalent to With ... End With in C#.

Here's a comparison chart for you that illustrates differences between Visual Basic and C#.

查看更多
forever°为你锁心
5楼-- · 2019-01-06 23:44

It's not equivalent, but would this syntax work for you?

Animal a = new Animal()
{
    SpeciesName = "Lion",
    IsHairy = true,
    NumberOfLegs = 4
};
查看更多
聊天终结者
6楼-- · 2019-01-06 23:54

There is no equivalent, but I think discussing a syntax might be interesting!

I quite like;

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

Any other suggestions?

I cant imagine that adding this language feature would be difficult, essentially just a preprocessed.

EDIT:

I was sick of waiting for this feature, so here is and extension that achieves a similar behavior.

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

Usage;

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

EDIT: Interestingly it seems someone beat me to the punch, again, with this "solution". Oh well..

查看更多
Viruses.
7楼-- · 2019-01-06 23:54

I think the equivalent of the following VB:

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

Would be this is C#:

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

The only real difference is that in vb, the identifier doesn't have a name "q", but is simply a default identifier used when a period is encountered without any other identifier before it.

查看更多
登录 后发表回答