如何在VB.NET中创建通用属性?

时间:2009-12-08 20:00:59

标签: vb.net generics properties

我想做这样的事情:

Private _myCollection As IList(Of T)
Public Property MyProperty(Of T)() as IList(Of T)
    Get
        Return Me._myCollection 
    End Get
    Set(ByVal value As String)
        Me._myCollection = value
    End Set
End Property

基本上,我希望拥有一系列可能属于任何类型的物品。然后,我将能够做到这样的事情:

Dim myPropertyValue as <the type of some value>
if (MyProperty.Contains(<some value>))
    myPropertyValue = CType(MyProperty(<some value>), <the type of some value>)

我该怎么做?或者有比使用泛型类型更好的方法吗?

2 个答案:

答案 0 :(得分:8)

您可能必须创建一个通用类来执行此操作

Public Class MyClass(Of T)
    Private _myCollection As IList(Of T)
    Public Property MyProperty() as IList(Of T)
        Get
            Return Me._myCollection 
        End Get
        Set(ByVal value As String)
            Me._myCollection = value
        End Set
    End Property
End Class

答案 1 :(得分:0)

如果您不想转换whole class to a generic one,还可以在课程中添加通用程序(请参阅MSDN):

Public Function GetMyProperty(Of T) As T
   ....
End Function
Public Sub SetMyProperty(value as T)
   ...
End Sub

但它并不像物业那么优雅。