开发者

Creating a generic list of a generic type

开发者 https://www.devze.com 2023-03-16 07:20 出处:网络
I am trying to create a list of a generic type in vb.net 2.0 framework. This is the generic type definition:

I am trying to create a list of a generic type in vb.net 2.0 framework. This is the generic type definition:

----------
  Public Class GenericParamMap(Of T)

    Public Sub New(ByVal pParamName As String, ByVal pPropValue As T)
      mParamName = pParamName
      mPropValue = pPropValue
    End Sub

    Public Property ParamName() As Str开发者_开发知识库ing
      Get
        Return mParamName
      End Get
      Set(ByVal Value As String)
        mParamName = Value
      End Set
    End Property
    Private mParamName As String

    Public Property PropValue() As T
      Get
        Return mPropValue
      End Get
      Set(ByVal Value As T)
        mPropValue = Value
      End Set
    End Property
    Private mPropValue As T
  End Class
----------

And here is a method that would use a list of GenericParamMap passed in as a parameter:

Public Sub PopulateParamMap(ByVal pMap As List(Of GenericParamMap(Of T))
      pMap.Add(New GenericParamMap(Of Integer)("@region_id", RegionId))
      pMap.Add(New GenericParamMap(Of String)("@bus_addr1", BusAddress1))
      pMap.add(New GenericParamMap(Of Boolean)("@active_flag", ActiveFlag))
End Sub
----------

The compiler does not allow a "T" in the method's parameter because it's not defined, but I'm not sure how or where to define it. I thought it was okay to have a generic method definition. Does anyone have any ideas? Thanks


Your code doesn’t work because different instances of GenericParamMap don’t share a common base (except Object). That is, a Thing(Of Integer) is entirely unrelated to a Thing(Of String) as far as VB is concerned.

One way to solve this is to have your class implement an interface (or extend a base class) and then declare your list as List(Of ThatInterface). Note that you will lose the generic type information that way, but there is fundamentally no way around this – you simply can’t integers and strings alike (except as far as their common base class goes, which is Object), and thus you also cannot treat Thing(Of Integer) and Thing(Of String) alike.


I think you must use generic method like below:

Public Sub PopulateParamMap(Of T)(ByVal pMap As List(Of GenericParamMap(Of T))
   pMap.Add(New GenericParamMap(Of T)("@region_id", RegionId))
End Sub

but you can't use your method for different types at the same time such as string, Integer...

0

精彩评论

暂无评论...
验证码 换一张
取 消