Any Visual Basic 'With' analog in C#? [duplicate]
Possible Duplicate:
C# equivalent for Visual Basic keyword: 'With' ... 'End With'?
VB.NET
With Alpha.Beta.Gama.Eta.Zeta
a = .ZetaPropertyA
b = .ZetaPropertyB
c = .ZetaPropertyC
End With
C#?
a = Alpha.Beta.Gama.Eta.Zeta.ZetaPropertyA
b = Alpha.Beta.Gama.Eta.Zeta.ZetaPropertyB
c = Alpha.Beta.Gama.Eta.Zeta.ZetaPropertyC
Nope, doesn't exist.
Though you could shorten it a bit:
var z = Alpha.Beta.Gama.Eta.Zeta;
z.ZetaPropertyA = a;
z.ZetaPropertyB = b;
z.ZetaPropertyC = c;
for your other case:
var z = Alpha.Beta.Gama.Eta.Zeta;
a = z.ZetaPropertyA;
b = z.ZetaPropertyB;
c = z.ZetaPropertyC;
That should've been obvious though ;)
For new instances you can use object initializer:
Alpa.Beta.Gama.Eta = new Zeta
{
ZetaPropertyA = a,
ZetaPropertyB = b,
ZetaPropertyC = c
}
No, there's nothing like the with
construct in C#.
Sorry, C# doesn't have that. The object initializer @Jakub suggests might provide an alternative, or:
If you design Zeta
yourself, you could use the fluent interface design pattern. That would allow you to do:
Alpha.Beta.Gama.Eta.Zeta
.SetPropertyA(A)
.SetPropertyB(B)
.SetPropertyC(C);
Which comes close to what you want, at the expense of a lot of work elsewhere. And remember that a fluent interface is not always the best design choice.
Nope. The workaround is a (short) local variable name instead of with
. Adds a few characters per line, but you still end up with fully qualified references.
精彩评论