我经常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
?
我经常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
?
With
我会在开始块之前保留对实例的引用,然后Return
在你使用完成员之后保留它:
Dim myInstance = New MyObj(...)
With myInstance
.Prop1 = Val1
.Prop2 = Val2
End With
Return myInstance
您无需担心垃圾收集的影响,因为您创建的变量一旦返回就会超出范围。
好吧,我想答案是只要我可以更改相关对象的定义,我就可以这样做:
Public Class XC
Public Self As XC = Me
End Class
With New XC()
Dim x As XC = .Self
End With
您可以将 VB 对象初始值设定项语法与 Option Infer 一起使用:
Dim variable As New SomeClass With
{
.AString = "Hello",
.AnInteger = 12345
}
return variable
你仍然有一个变量,但它很干净。
如果你不想要这个变量,你可以试试这样的代码:
Return New SomeClass With
{
.AString = "Hello",
.AnInteger = 12345
}
但是,我不相信这种语法允许您调用实例上的方法。我认为你只能设置属性。