包含派生类成员的类列表

时间:2016-07-28 13:10:58

标签: vb.net

我想创建具有其设计成员的不同设备类的列表。这可能吗?

Public lstDevices As New List(Of Device)

    Public Class Device
        Public strName As String
        Public iKind As Integer 
    End Class

然后我将使用特定类型的设备命名为Printer

    Public Class Printer : Inherits Device
        public shared  iAge as integer
    End Class

我怎样才能到达前。

lstDevices.Find(Function(p) p.strName = strName).iAge = 10

如果我clsPrinter = new Printer() 我可以到达clsPrinter.iAge

但是有了列表,这可能吗?

2 个答案:

答案 0 :(得分:0)

lstDevices - 列表存储Devices,因此Printer的父类具有iAge属性。你必须适当地施展它。但您还必须将List.Find的结果存储在变量中:

Dim foundDevice As Device = lstDevices.Find(Function(p) p.strName = strName)
If foundDevice IsNot Nothing AndAlso TypeOf foundDevice Is Printer Then
    Dim foundPrinter As Printer = DirectCast(foundDevice, Printer)
    foundPrinter.iAge = 10
End If

另一个不错的LINQ方法是:

Dim foundPrinters = From p In lstDevices.OfType(Of Printer)()
                    Where p.strName = strName
Dim firstPrinter As Printer = foundPrinters.FirstOrdefault()

答案 1 :(得分:0)

我只想提醒您,Printer类的iAge属性是共享属性

我比LINQ查询更喜欢LINQ方法。所以我尝试将Tim的查询转换为LINQ方法(减去where标准)。我故意使用First()而不是FirstOrDefault()。代码如下所示:

module loading failed: file security/ir.model.access.csv could not be processed:
No matching record found for external id: test_1.stock_picking_manager in field 'Group'

VS在这些行中显示警告:

Module Module1

    Public lstDevices As New List(Of Device)

    Sub Main()

        lstDevices.Add(New Printer() With {.strName = "Epson", .iKind = 1})
        lstDevices.Add(New Printer() With {.strName = "HP", .iKind = 2})

        lstDevices.OfType(Of Printer).First().iAge = 10
        Console.WriteLine(lstDevices.OfType(Of Printer).First().iAge)

        Console.ReadKey(True)

    End Sub

End Module

Public Class Device
    Public strName As String
    Public iKind As Integer
End Class

Public Class Printer : Inherits Device
    Public Shared iAge As Integer
End Class

两行的警告是:

  

访问共享成员,常量成员,枚举成员或嵌套类型   通过一个实例;不会评估合格表达。

这意味着表达式不会被评估,因为iAge是一个共享属性。即使我删除了我在列表中添加打印机实例的2行,代码也不会抛出任何异常。这是因为iAge属性与Printer类绑定,而不是Printer类的实例。

lstDevices.OfType(Of Printer).First().iAge = 10
Console.WriteLine(lstDevices.OfType(Of Printer).First().iAge)

因此可以将2行简化为:

Sub Main()

    'lstDevices.Add(New Printer() With {.strName = "Epson", .iKind = 1})
    'lstDevices.Add(New Printer() With {.strName = "HP", .iKind = 2})

    ' these 2 lines won't throw any exceptions eventhough the list is empty
    lstDevices.OfType(Of Printer).First().iAge = 10
    Console.WriteLine(lstDevices.OfType(Of Printer).First().iAge)

    Console.ReadKey(True)

End Sub

如果从iAge中删除Shared关键字,那么如果列表为空,则代码可能会抛出异常。 Tim的代码是安全的,因为他使用FirstOrDefault(),你可以检查firstPrinter是否为null(null),然后使用iAge属性。