Does C# have any equivalent for VB6
With
End With
There's nothing quite equivalent, but C# 3 gained the ability to set properties on construction:
var person = new Person { Name = "Jon", Age = 34 };
And collections:
var people = new List<Person>
{
new Person { Name = "Jon" },
new Person { Name = "Holly"}
};
It's definitely not a replacement for all uses of With
, but worth knowing for some of them.
C# does not have any equivalent syntax. The closest are object initializers, but they are not the same:
var obj = new SomeThing {
Height = 100,
Text = "Hello, World",
ForeColor = System.Drawing.Color.Green
}
No.
What comes close are object and list initializers.
Person p = new Person()
{
FirstName = "John",
LastName = "Doe",
Address = new Address()
{
Street = "1234 St.",
City = "Seattle"
}
};
It is by no means an equivalent, however, if it is the typing you're trying to reduce, you can do.
{
var o = myReallyReallyReallyReallyLongObjectName;
o.Property1 = 1;
o.Property2 = 2;
o.Property3 = 3;
}
There is no C# equivalent to Visual Basic's With
keyword.
There is no equivalent in c# -> read more here in the comments http://blogs.msdn.com/b/csharpfaq/archive/2004/03/11/why-doesn-t-c-have-vb-net-s-with-operator.aspx
One near-equivalent would be calling a method that is a member of a class. You don't have to repeatedly name the owning object inside class members - it's implicit in the fact that the function is a member, called for a given instance.
I doubt a direct equivalent of With/End With is a good idea in C# for this reason. If you found yourself typing an object's name over and over in a given scope, it's a good indication that the code in question would make a good method on that object's class.
There is no direct equivalent. You can set properties on construction, as others explained, or you can assign your expression to a variable with a short name. The following should be semantically equivalent:
With <expression>
.something ...
.somethingElse ...
End With
var w = <expression>;
w.something ...
w.somethingElse ...
精彩评论