访问派生类中接口所需的属性

时间:2014-11-01 15:08:43

标签: vb.net inheritance interface

假设基类为“狗”......

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

然后,假设Dog可以实现两个可能的接口......

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

然后我定义了两个派生自Dog ...

的类
Public Class Shepherd
  Inherits Dog
  Implements iGuardDog
End Class

Public Class Poodle
  Inherits Dog
  Implements iPlayfulDog
End Class

所以,我有一个List(Of Dog)并添加了一些Shepherds和Poodles。现在我想找到护卫犬并检查他们的巡逻范围......

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基类;只是一个界面。

2 个答案:

答案 0 :(得分:1)

您可以在IEnumerable上使用扩展程序OfType

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

此方法可以:

  

根据指定的类型过滤IEnumerable的元素。

因此,它只会使用实现您的界面iGuardDog的元素。

PS:在.NET中,您通常使用大写字母前缀接口" i" (所以你的界面是IGuardDog)。另请参阅naming conventions

答案 1 :(得分: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