【发布时间】:2009-06-30 12:38:25
【问题描述】:
【问题讨论】:
-
"with" 实际上早在 VB 之前就已经存在了。它存在于 Pascal 中,用于处理记录类型。不知道 Pascal 是否从其他地方借鉴了这个想法。
标签: c# vb.net with-statement
【问题讨论】:
标签: c# vb.net with-statement
这不是等效的,但是这种语法对你有用吗?
Animal a = new Animal()
{
SpeciesName = "Lion",
IsHairy = true,
NumberOfLegs = 4
};
【讨论】:
C# 没有与之等效的语言结构。
【讨论】:
没有等价物,但我认为讨论语法可能很有趣!
我很喜欢;
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..
});
编辑:有趣的是,似乎有人再次用这个“解决方案”击败了我。哦,好吧..
【讨论】:
x = LongInstanceOfPersonVariableName; x.AgeIntVar = 21; //etc.
我觉得相当于下面的VB:
With SomeObjectExpression()
.SomeProperty = 5
.SomeOtherProperty = "Hello"
End With
这是C#:
{
Var q=SomeOtherExpression();
q.SomeProperty = 5;
q.SomeOtherProperty = "Hello";
}
唯一真正的区别是,在 vb 中,标识符没有名称“q”,而只是一个默认标识符,用于在遇到句号之前没有任何其他标识符时使用。
【讨论】:
SomeOtherExpression 或属性设置器做什么,我认为他们中的任何人都无法通过使用反射检查来确定上述代码 sn-ps 中的哪个 except 正在评估它们调用上下文。反射可以区分调用上下文这一事实使它们完全等效,但在所有其他方面,行为都是相同的。
C# 中没有与 With ... End With 等价物。
这里是 a comparison chart,它说明了 Visual Basic 和 C# 之间的差异。
【讨论】:
C# 中没有等效的结构。这是 Visual Basic 6.0 / VB.NET 功能。
【讨论】: