泛型類型在應用程序運行時即時創建。當您參考GenericClass(Of String, Integer)
時,它會將該類的自定義版本加載到內存中。當您稍後參考GenericClass(Of String, Long)
時,它會將另一個單獨的自定義類加載到內存中。在加載類之前,您不能訪問任何成員,包括構造函數。在你調用其中一個構造函數之前,你總是必須參考GenericClass(Of String, V)
。
有幾個選項可供您使用。沒有一個比原始代碼更可讀。主要問題是您只能通過指定K
和V
類型來引用該類。
方法1:靜態方法
使用共享/靜態Create
方法來創建對象。
Public Class GenericClass(Of K, V)
Private _Dictionary As Dictionary(Of K, V)
Sub New()
_Dictionary = New Dictionary(Of K, V)
End Sub
Public Shared Function Create(sc As StringComparer) As GenericClass(Of String, V)
Dim NewObject As New GenericClass(Of String, V)
' TODO: Initialise object.
Return NewObject
End Function
End Class
創建對象有:
Dim sc As StringComparer = New StringComparer()
Dim MyObject As GenericClass(Of String, ValueType) = GenericClass(Of String, ValueType).Create(sc)
方法2:繼承類
創建一個繼承類,強制執行K
類型爲String
。
Dim sc As StringComparer = New StringComparer()
Dim MyObject As New NotSoGenericClass(Of ValueType)(sc)
或
Dim sc As StringComparer = New StringComparer()
Dim MyObject As GenericClass(Of String, ValueType) = New NotSoGenericClass(Of ValueType)(sc)
方法3:靜態類
您可以創建一個
Public Class NotSoGenericClass(Of V)
Inherits GenericClass(Of String, V)
Public Sub New(sc As StringComparer)
MyBase.New()
' TODO: Initialise object.
End Sub
End Class
您與創建對象靜態類(Private Sub New
防止它被瞬時化)或包含Create
方法的模塊。這個與GenericClass具有相同的名稱,但沒有類型說明符。
Dim sc As StringComparer = New StringComparer()
Dim MyObject As GenericClass(Of String, ValueType) = GenericClass.Create(Of ValueType)(sc)
方法4:
Public Class GenericClass
Private Sub New()
End Sub
Public Shared Function Create(Of V)(sc As StringComparer) As GenericClass(Of String, V)
Dim NewObject As New GenericClass(Of String, V)
' TODO: Initialise object.
Return NewObject
End Function
End Class
您與創建對象拋出一個異常
您可以創建,如果它的正確使用拋出異常的構造器。這裏的問題是,IDE不reccognise此限制,將讓構造函數無效K
類型調用。
Sub New(sc As StringComparer)
If GetType(K) IsNot GetType(String) Then Throw New InvalidCastException("Type K must be String for this constructor.")
_Dictionary = New Dictionary(Of K, V)
End Sub
您創建的對象:
Dim sc As StringComparer = New StringComparer()
Dim MyObject As New GenericClass(Of String, ValueType)(sc)
但是,這將引發異常:
Dim sc As StringComparer = New StringComparer()
Dim MyObject As New GenericClass(Of Object, ValueType)(sc)
@Enimga,更改'Protected'到'Public',滴'MyStringClass'都在一起,和你有一個近乎完美的解決方案。 Dim x As New MyClass(Of String,Integer)(StringComparer.InvariantCulture)'作品。當然,你在那裏也有效。 –
我幾乎錯過了實現IEqualityComparer(Of K)的解決方案 - 輝煌!謝謝! – ic3b3rg