How do I create a generic property in VB.NET?

自作多情 提交于 2020-01-29 15:34:21

问题


I'd like to do something like this:

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

Basically, I want to have a collection of items that may be of any type. Then, I'll be able to do something like this:

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

How can I do this? Or is there a better way than using a generic type?


回答1:


You may have to create a generic class to do this

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



回答2:


If you do not want to convert your whole class to a generic one you could also add generic procedures to your class (see MSDN):

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

But it is not as elegant as the properties.



来源:https://stackoverflow.com/questions/1869451/how-do-i-create-a-generic-property-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!