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

Vb.net 访问派生类中接口所需的属性,vb.net,inheritance,interface,Vb.net,Inheritance,Interface,假设一个基类为“Dog” 然后,假设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 Interfa

假设一个基类为“Dog”

然后,假设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
所以,我有一张(狗的)名单,加上一些牧羊人和贵宾犬。现在我要找到警犬并检查它们的巡逻范围

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

您可以将每只狗转换为
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

您可以在
IEnumerable
上使用扩展方法:

For Each d As iGuardDog In MyDocs.OfType(Of iGuardDog)()
    Debug.WriteLine(d.PatrolRange)
Next
此方法的作用是:

根据指定类型筛选IEnumerable的元素

因此,它将只接受实现接口的元素
iguardog


在.NET中,您通常在接口前面加上大写字母“i”(因此您的接口应该是IGuardDog)。另请参见。

这正是我需要的,谢谢!还感谢您指出接口命名约定。
For Each d As iGuardDog In MyDocs.OfType(Of iGuardDog)()
    Debug.WriteLine(d.PatrolRange)
Next