泛型类型在应用程序运行时即时创建。当您参考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