Constructing an object and calling a method without assignment in VB.Net

做~自己de王妃 提交于 2019-12-22 07:57:13

问题


I'm not entirely sure what to call what C# does, so I haven't had any luck searching for the VB.Net equivalent syntax (if it exists, which I suspect it probably doesn't).

In c#, you can do this:

public void DoSomething() {
    new MyHelper().DoIt(); // works just fine
}

But as far as I can tell, in VB.Net, you must assign the helper object to a local variable or you just get a syntax error:

Public Sub DoSomething()
    New MyHelper().DoIt() ' won't compile
End Sub

Just one of those curiosity things I run into from day to day working on mixed language projects - often there is a VB.Net equivalent which uses less than obvious syntax. Anyone?


回答1:


The magic word here is Call.

Public Sub DoSomething()
    Call (New MyHelper()).DoIt()
    Call New MyHelper().DoIt()
End Sub



回答2:


Gideon Engelberth is right about using Call. It is the best option.

Another option is to use a With statement:

With New MyHelper()
    .DoIt()
End With


来源:https://stackoverflow.com/questions/2648700/constructing-an-object-and-calling-a-method-without-assignment-in-vb-net

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