VB.Net calling New without assigning value

白昼怎懂夜的黑 提交于 2019-12-10 15:57:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!