odi*_*seh 19 c# vb.net with-statement
我知道C#有using关键字,但会using自动处理对象.
With...End With在Visual Basic 6.0中是否存在等价?
tom*_*ing 34
它不等同,但这种语法对你有用吗?
Animal a = new Animal()
{
SpeciesName = "Lion",
IsHairy = true,
NumberOfLegs = 4
};
Run Code Online (Sandbox Code Playgroud)
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)
编辑:有趣的是,似乎有人用这个"解决方案"再次打败了我.那好吧..
我认为相当于以下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",而只是在遇到句点而没有任何其他标识符之前使用的默认标识符.
| 归档时间: |
|
| 查看次数: |
46737 次 |
| 最近记录: |