问题
In C# I can do this:
new SomeObjectType("abc", 10);
In other words, I can call new without assigning the created instance to any variable. However, in VB.Net it seems I cannot do the same thing.
New SomeObjectType("abc", 10) ' syntax error
Is there a way to do this in VB.Net?
回答1:
See the answers to this other SO Answer
So this should work:
With New SomeObjectType("abc", 10)
End With
回答2:
The following works on the Mono VB compiler (vbnc, version 0.0.0.5914, Mono 2.4.2 - r):
Call New SomeObjectType("abc", 10)
Notice the required Call.
回答3:
That should be the correct syntax, e.g.
Dim name As New String
Dim url As New Uri("http://www.somedomain.com")
Have you got some more code where this is happening?
回答4:
One can define a Sub to discard the constructed object:
Sub gobble(dummy As Object)
End Sub
Then call the constructor as follows:
gobble(New SomeClass())
I'm using this approach in tests when I test exceptions in constructors. I construct the object in a lambda and pass that lambda to a function that checks for the Exception. Fits nicely on a line.
assertThrows(Of ArgumentOutOfRangeException)(Sub() gobble(New ClassUnderTest("stuff")))
来源:https://stackoverflow.com/questions/3015489/vb-net-calling-new-without-assigning-value