C# 中“With...End With”的等价物?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1063429/
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
Equivalence of "With...End With" in C#?
提问by odiseh
I know that C# has the using
keyword, but using
disposes of the object automatically.
我知道 C# 有using
关键字,但会using
自动处理对象。
Is there the equivalence of With...End With
in Visual Basic 6.0?
With...End With
在Visual Basic 6.0 中是否有等价物?
采纳答案by Philippe Leybaert
C# doesn't have an equivalent language construct for that.
C# 没有对应的语言结构。
回答by Joseph
There's no equivalent to With ... End With in C#.
在C# 中没有与 With ... End With 等价的东西。
Here's a comparison chartfor you that illustrates differences between Visual Basic and C#.
这是一个比较图表,说明了 Visual Basic 和 C# 之间的差异。
回答by JaredPar
回答by tomfanning
It's not equivalent, but would this syntax work for you?
它不是等价的,但是这种语法对你有用吗?
Animal a = new Animal()
{
SpeciesName = "Lion",
IsHairy = true,
NumberOfLegs = 4
};
回答by supercat
I think the equivalent of the following VB:
我认为相当于以下VB:
With SomeObjectExpression()
.SomeProperty = 5
.SomeOtherProperty = "Hello"
End With
Would be this is C#:
这将是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.
唯一真正的区别是在 vb 中,标识符没有名称“q”,而只是遇到句点时使用的默认标识符,而在它之前没有任何其他标识符。
回答by expelledboy
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..
编辑:有趣的是,似乎有人再次用这个“解决方案”击败了我。那好吧..