2013-01-18 100 views
1

假設我有:如何在VB.Net中擴展一個類的構造函數?

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 
+2

簡短的回答:你不能這樣做。 – sloth

回答

3

cannot extend constructors與擴展方法。擴展方法是幾乎相同的staticshared在VB)方法,它允許寫的

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} 
+0

確實存在另一種方式嗎?我無法訪問'clsTest',但我想擴展它。 –

+1

你有沒有試過從'clsTest'繼承? – tcarvin

+0

是的,但沒有任何方式沒有繼承? (擴展原始類)我想使用:'Dim t1 AS新的clsTest(「我的名字」,2)''而不是'Dim t1 AS New Foo(「my name」,2)'。 –

相關問題