C# 中“With...End With”的等价物?[复制]
-
21-08-2019 - |
题
这个问题在这里已经有答案了:
- 与 C# 中的块等效吗? 15 个答案
我知道 C# 有 using
关键字,但是 using
自动处理该对象。
是否有等价的 With...End With
在 视觉基本6.0?
解决方案
C# 没有相应的语言结构。
其他提示
它并不等效,但是这种语法对您有用吗?
Animal a = new Animal()
{
SpeciesName = "Lion",
IsHairy = true,
NumberOfLegs = 4
};
没有等效的,但我认为讨论语法可能很有趣!
我相当喜欢;
NameSpace.MyObject.
{
active = true;
bgcol = Color.Red;
}
还有其他建议吗?
我无法想象添加这种语言功能会很困难,本质上只是一个预处理。
编辑:
我厌倦了等待这个功能,所以这里是实现类似行为的扩展。
/// <summary>
/// C# implementation of Visual Basics With statement
/// </summary>
public static void With<T>(this T _object, Action<T> _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”,而只是在遇到句点且前面没有任何其他标识符时使用的默认标识符。
C# 中没有等效的结构。这是一个 Visual Basic 6.0 / 网络 特征。
不隶属于 StackOverflow