C#中“与…结束”的等价性?
我知道C#有using
关键字,但是自动using
对象处理。
在Visual Basic 6.0中是否存在With...End With
的等价性?
C#没有相应的语言结构。
它不等同,但这种语法对你有用吗?
Animal a = new Animal() { SpeciesName = "Lion", IsHairy = true, NumberOfLegs = 4 };
没有等价物,但我认为讨论语法可能很有趣!
我相当喜欢;
NameSpace.MyObject. { active = true; bgcol = Color.Red; }
还有其他建议吗?
我无法想象添加这种语言function会很困难,基本上只是预处理。
编辑:
我厌倦了等待这个function,所以这里和扩展实现了类似的行为。
/// /// C# implementation of Visual Basics With statement /// public static void With(this T _object, Action _action) { _action(_object); }
用法;
LongInstanceOfPersonVariableName.With(x => { x.AgeIntVar = 21; x.NameStrVar = "John"; x.NameStrVar += " Smith"; //etc.. });
编辑:有趣的是,似乎有人用这个“解决方案”再次打败了我。 那好吧..
我认为相当于以下VB :
With SomeObjectExpression() .SomeProperty = 5 .SomeOtherProperty = "Hello" End With
这是C# :
{ Var q=SomeOtherExpression(); q.SomeProperty = 5; q.SomeOtherProperty = "Hello"; }
唯一真正的区别在于,在vb中,标识符没有名称“q”,但它只是在遇到句点而没有任何其他标识符之前使用的默认标识符。
没有相当于With … End With in C# 。
这是一个比较图表 ,说明了Visual Basic和C#之间的差异。
C#中没有等效的结构。 这是Visual Basic 6.0 / VB.NETfunction。