1

假设我有:

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
4

1 回答 1

3

不能使用扩展方法扩展构造函数。static扩展方法与(shared在 VB 中)允许编写的方法几乎相同

instanceOfMyClass.SomeExtension(someParameter)

代替

MyClass.SomeExtension(instanceOfMyClass, someParameter)

如果你没有访问权限clsTest(你真的应该改变你的命名)但你想扩展它,你也可以创建一个继承自它的新类:

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}
于 2013-01-18T13:32:15.243 回答