假设我有:
Public Class clsTest
Public Sub New()
End Sub
Public Sub New(name_ As String)
'...
End Sub
End Class
我想扩展这个类:
<System.Runtime.CompilerServices.Extension> _
Public Sub methodA(t1 As clsTest, i As Integer)
'...
End Sub
但我不能将构造函数扩展为:
<System.Runtime.CompilerServices.Extension> _
Public Sub New(t1 As clsTest, name_ As String, i As Integer)
'...
End Sub
答案 0 :(得分:3)
您cannot extend constructors有扩展方法。扩展方法与允许写入的static
(VB中的shared
)方法几乎相同
instanceOfMyClass.SomeExtension(someParameter)
而不是
MyClass.SomeExtension(instanceOfMyClass, someParameter)
如果你没有访问clsTest
(你应该真的改变你的namings)但是你想要扩展它,你也可以创建一个继承它的新类:
Public Class Foo ' consider this as your clsTest
Public Sub New()
End Sub
Public Property Name As String
Public Property Number As Int32
Public Sub New(name As String)
Me.Name = Name
End Sub
End Class
Public Class Bar
Inherits Foo
Public Sub New(name As String, i As Integer)
MyBase.Name = name
MyBase.Number = i
End Sub
End Class
最后,也许你不需要扩展课程,但你只是想找一种方便的方法来在一行中初始化它:
Dim foo = New Foo("test") With {.Number = 4711}