可能是重复问题: C#中“With…End With”的等效性?
我不知道这个问题是否已经被问过,我也不是一个大 VB.NET 的粉丝。但是,在 C#中我缺少的一种语法是 With
语法。
在 VB.NET 中,您可以编写:
Dim sb As New StringBuilder
With sb
.Append("foo")
.Append("bar")
.Append("zap")
End With
我是否错过了C#中可以完成同样操作的语法?
可能是重复问题: C#中“With…End With”的等效性?
我不知道这个问题是否已经被问过,我也不是一个大 VB.NET 的粉丝。但是,在 C#中我缺少的一种语法是 With
语法。
在 VB.NET 中,您可以编写:
Dim sb As New StringBuilder
With sb
.Append("foo")
.Append("bar")
.Append("zap")
End With
我是否错过了C#中可以完成同样操作的语法?
StringBuilder sb = new StringBuilder()
.Append("foo")
.Append("bar")
.Append("zap");
With myObject
.Property1 = "Value1"
.Property2 = "Value2"
.Method1()
End With
这段代码中,myObject
是一个对象,使用 With/End With 语法可以简化对该对象属性和方法的调用。但如果在 With
块内部使用过多的点符号来引用对象成员,则代码可读性就会下降。 - ken2kVB的With
语句没有直接的对应物。
然而,需要注意的是StringBuilder.Append
返回StringBuilder
实例,因此以下代码等同于您原来的代码:
sb.Append("foo").Append("bar").Append("zap");
sb.Append("foo")
.Append("bar")
.Append("zap");
对于 New Type With
,有一个相等的替代品:
var obj = new Type {
PropName = Value,
PropName = Value
};
但不适用于普通的With
。
不,没有等价的语法。
With
是VB/VB.NET专用的。
这个功能只有 Visual Basic 才有,其他语言没有。
C# 中没有包含这个功能的主要原因是它可能会导致代码混乱,例如在使用嵌套的 With
语句时。
sb.Append("foo")
代替with
语句确实更好吗?我在 VB.NET 编程已经有12年了,从来没有理解过使用 with 语句的好处。这只是另一件你必须每次查找的东西(那是什么来着?)。 - Tim Schmelter