简体   繁体   English

VB.NET List(Of T)-我可以用它保存几种类型的项目吗?

[英]VB.NET List(Of T) - Can I use it to hold items of several types?

Assuming a base type of "Message"... 假设基本类型为“消息” ...

Public Class Message
   Public ID As Int64
   Public Text As String
   Public MessageType as String
End Class

...and then two derived classes... ...然后是两个派生类...

Public Class PhoneMessage
   Inherits Message
   Public MessageLength As Int64
End Class

Public Class MailMessage
   Inherits Message
   Public Postage As Int64
End Class

I would like to have one collection of Message objects which can be either PhoneMessages or MailMessages, so that I can iterate through the list and deal with each message based on what type it happens to be. 我想要一个Message对象的集合,可以是PhoneMessages或MailMessages,以便我可以遍历列表并根据碰巧的类型处理每条消息。

Attempting just to use .Add() fails, saying that I can't add an item of type PhoneMessage to a List(Of Message). 尝试仅使用.Add()失败,表示无法将PhoneMessage类型的项添加到List(Of Message)。 Is there some elegant way to accomplish what I'm trying to do? 有什么优雅的方法可以完成我想做的事情吗? I had thought I could accomplish this with generics, but I think there's a gap in my understanding. 我以为可以使用泛型来完成此操作,但我认为我的理解存在差距。 If it can be accomplished in .NET 2.0, that would be ideal. 如果可以在.NET 2.0中完成,那将是理想的选择。

Thank you in advance. 先感谢您。

The way you describe how you are adding the items to the list should work. 描述如何将项目添加到列表的方式应该可以使用。 Perhaps there is something missing from your code? 也许您的代码中缺少什么? With the code you gave for your classes, this should do the trick: 使用为类提供的代码,这应该可以解决问题:

    Dim phoneMessage As New PhoneMessage()
    Dim mailMessage As New MailMessage()

    Dim messageList As New List(Of Message)()

    messageList.Add(phoneMessage)
    messageList.Add(mailMessage)

您只需要将PhoneMessage强制转换为其基类Message

Odd, that really ought to work. 奇怪的是,这确实应该起作用。 Have you tried using CType() or DirectCast to cast it to a Message? 您是否尝试过使用CType()或DirectCast将其转换为消息?

Here's some code that proves that scottman666 is correct: 这是一些代码,证明scottman666是正确的:

Public Class InheritanceTest
    Public Class Message
        Public ID As Int64
        Public Text As String
        Public MessageType As String
    End Class

    Public Class PhoneMessage
        Inherits Message
        Public MessageLength As Int64

    End Class

    Public Class MailMessage
        Inherits Message
        Public Postage As Int64
    End Class

    Public Shared Sub ListTest()
        Dim lst As New List(Of Message)
        Dim msg As Message

        msg = New PhoneMessage()

        lst.Add(msg)
        lst.Add(New MailMessage())
    End Sub
End Class

I would recommend that you consider using Overidable and MustOveride functions to make polymorphic objects. 我建议您考虑使用Overidable和MustOveride函数制作多态对象。 There is a good way to handle the design pattern your working with. 有一个很好的方法来处理您使用的设计模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM