我只是想提醒你,打印機類的iAge屬性是共享的物業。
我比LINQ查詢更喜歡LINQ方法。所以我嘗試將Tim的查詢轉換爲LINQ方法(減去where標準)。我故意使用First()而不是FirstOrDefault()。代碼如下所示:
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
VS顯示這些行警告:
lstDevices.OfType(Of Printer).First().iAge = 10
Console.WriteLine(lstDevices.OfType(Of Printer).First().iAge)
兩條線路的警告是:共享成員,常量成員,枚舉成員的
Access或通過一個實例嵌套類型 ;符合條件的表達式將不會被評估。
這意味着表達式將不會被評估,因爲iAge是一個共享屬性。即使我刪除了添加打印機實例到列表中的2行,代碼也不會拋出任何異常。這是因爲iAge屬性綁定到Printer類,而不是Printer類的實例。
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
因此,有2條線可以簡化爲:如果您從iAge Shared關鍵字
'lstDevices.OfType(Of Printer).First().iAge = 10
'Console.WriteLine(lstDevices.OfType(Of Printer).First().iAge)
Printer.iAge = 10
Console.WriteLine(Printer.iAge)
,那麼代碼可能,如果列表是空的拋出異常。 Tim的代碼是安全的,因爲他使用FirstOrDefault(),您可以檢查firstPrinter是否爲空(null),然後使用iAge屬性。
來源
2016-07-28 14:25:36
Han
對,謝謝。但我需要創建一個新的設備?有沒有一種方法可以在沒有創建的情況下伸出手? Dim tmpDevice As Printer = CType(lstDevices.Find(Function(p)p。strName = strName),打印機) – kwestia
@kwestia:我不明白,我沒有創建任何東西。當然,你也可以使用你的一行。但唯一的區別是,如果設備不是打印機或沒有找到設備,則會引發異常。您可以使用TryCast代替。但我更喜歡第二種LINQ方法。 –
對,它不是新變量foundDevice,但施放:)我的意思是直接從列表到達設備,如lstDevices.Find(Function(p)p.strName = strName).iAge = 10。但無論如何你的解決方案的作品,謝謝:) – kwestia