2014-11-01 92 views
-1

假設一個基類「狗」的通過接口所需要的屬性...訪問在派生類

Public Class Dog 
    Public Property Breed as String 
    Public Property Weight as Integer 
End Class 

然後,假定有一些狗可以實現兩個可能的接口...

Public Interface iGuardDog 
    Property PatrolRange as Integer 
    Property BarkVolume as Integer 
End Interface 


Public Interface iPlayfulDog 
    Property RunSpeed as Integer 
    Property FrisbeeSkill as Integer 
End Interface 

然後我定義了從犬推導出兩個班...

Public Class Shepherd 
    Inherits Dog 
    Implements iGuardDog 
End Class 

Public Class Poodle 
    Inherits Dog 
    Implements iPlayfulDog 
End Class 

所以,我有一個List(狗),並添加一些牧羊人和Poodle。現在我想找到護衛犬,並檢查他們的巡邏範圍...

For Each D as Dog in MyDogs.Where(Function(x) TypeOf x is iGuardDog) 
    debug.Writeline(D.PatrolRange) '' This line throws an exception because it can't see the PatrolRange property 
Next 

什麼是正確的方式來完成我想做的事情?我沒有GuardDog基類;只是一個界面。

回答

1

你可以使用擴展方法OfTypeIEnumerable

For Each d As iGuardDog In MyDocs.OfType(Of iGuardDog)() 
    Debug.WriteLine(d.PatrolRange) 
Next 

此方法執行:

篩選IEnumerable根據指定類型的元素。

因此,它只會採用實現您的接口iGuardDog的元素。 PS:在.NET中,您通常會在首字母爲「i」前添加接口(因此您的接口將是IGuardDog)。另見naming conventions

+0

這正是我需要的,謝謝!另外感謝您指出接口命名約定。 – DWRoelands 2014-11-01 18:13:20

0

您可以將每隻狗分配爲IGuardDog類型。它只會給你訪問IGuardDog的性質,而不是那些基Dog類的,但你有那些在您D變量:

Dim thisDog As iGuardDog 
For Each D As Dog In MyDogs.Where(Function(x) TypeOf x Is iGuardDog) 
    thisDog = CType(D, iGuardDog) 
    Debug.WriteLine(String.Format("wt: {0}, range: {1}", 
            D.Weight.ToString, thisDog.PatrolRange.ToString)) 
Next