2012-04-25 171 views
0

有誰知道一種獲取接口屬性的基礎屬性名稱的方法嗎?接口,屬性和反射

例如,拿我已經稍微修改的接口Juliet's很好的例子:

Module1 

Interface ILifeform 
    ReadOnly Property Name() As String 
    Sub Speak() 
    Sub Eat() 
End Interface 

Class Dog 
    Implements ILifeform 

    Public ReadOnly Property Name() As String Implements ILifeform.Name 
     Get 
      Return "Doggy!" 
     End Get 
    End Property 

    Public Sub Talk() Implements ILifeform.Speak 
     Console.WriteLine("Woof!") 
    End Sub 

    Public Sub Eat() Implements ILifeform.Eat 
     Console.WriteLine("Yum, doggy biscuits!") 
    End Sub 
End Class 

Class Ninja 
    Implements ILifeform 

    Public ReadOnly Property Name() As String Implements ILifeform.Name 
     Get 
      Return "Ninja!!" 
     End Get 
    End Property 

    Public Sub Speak() Implements ILifeform.Speak 
     Console.WriteLine("Ninjas are silent, deadly killers") 
    End Sub 

    Public Sub Eat() Implements ILifeform.Eat 
     Console.WriteLine("Ninjas don't eat, they wail on guitars and kick ass") 
    End Sub 
End Class 

Class Monkey 
    Implements ILifeform 


    Public ReadOnly Property Name() As String Implements ILifeform.Name 
     Get 
      Return "Monkey!!!" 
     End Get 
    End Property 

    Public Sub Speak() Implements ILifeform.Speak 
     Console.WriteLine("Ook ook") 
    End Sub 

    Public Sub Eat() Implements ILifeform.Eat 
     Console.WriteLine("Bananas!") 
    End Sub 
End Class 


Sub Main() 
    Dim lifeforms As ILifeform() = New ILifeform() {New Dog(), New Ninja(), New Monkey()} 
    For Each x As ILifeform In lifeforms 
     HandleLifeform(x) 
    Next 

    Console.ReadKey(True) 
End Sub 

Sub HandleLifeform(ByVal x As ILifeform) 
    Console.WriteLine("Handling lifeform '{0}'", x.Name) 
    x.Speak() 
    x.Eat() 
    Console.WriteLine() 
End Sub 
End Module 

狗類,實施「說話」的屬性被稱爲「對話」。

如果我收到一個狗對象作爲'對象'類型,我可以這樣做嗎?

If TypeOf(object) Is ILifeForm Then 
    Dim str as string = CType(object, ILifeForm).GetUnderLyingPropertyName("Speak")) 
    ' str now contains "Talk" 
End If 
+0

你爲什麼要命名實現你的接口方法的方法呢?從設計的角度來看,這很糟糕。 – Tejs 2012-04-25 15:49:45

+0

@Tejs我甚至沒有意識到vb.net會允許這種情況發生...... – asawyer 2012-04-25 15:50:08

+0

是的,我也沒有。目前正在閱讀。我認爲它源自於他們能夠確定顯式接口實現的含義與C#相比 – Tejs 2012-04-25 15:52:41

回答

-2

爲什麼這樣做:

CType(object, ILifeForm).GetUnderLyingPropertyName("Speak")) 

則簡單得多執行此操作時:

CType(object, ILifeForm).Speak 

? 工作完成。這是一個經典的多態。

+0

你不明白這個問題。 – 2015-05-02 00:33:08