我经常使用with
创建一个对象并运行它的方法。它使代码看起来干净:
With New MyObj(...)
.Prop1 = Val1
.Prop2 = Val2
.Run()
End With
然而,有时我想要返回对象:
With New MyObj(...)
.Prop1 = Val1
.Prop2 = Val2
Return .Me
End With
但并非所有对象都有Me(this)属性,那么如何在with
中引用相关对象?
答案 0 :(得分:2)
我会在启动With
块之前保留对实例的引用,然后在使用成员后保留Return
:
Dim myInstance = New MyObj(...)
With myInstance
.Prop1 = Val1
.Prop2 = Val2
End With
Return myInstance
您无需担心垃圾收集的影响,因为无论如何,您创建的变量都会超出范围。
答案 1 :(得分:0)
好吧,我想答案是,只要我能改变有问题对象的定义,我就可以这样做:
Public Class XC
Public Self As XC = Me
End Class
With New XC()
Dim x As XC = .Self
End With
答案 2 :(得分:0)
您可以将VB对象初始值设定语法与Option Infer:
一起使用Dim variable As New SomeClass With
{
.AString = "Hello",
.AnInteger = 12345
}
return variable
你还有一个变量,但它很干净。
如果您不想要变量,可以尝试使用以下代码:
Return New SomeClass With
{
.AString = "Hello",
.AnInteger = 12345
}
我不相信这种语法允许您调用实例上的方法。我认为你只能设置属性。