【发布时间】:2012-05-06 08:10:48
【问题描述】:
有人知道获取接口属性的基础属性名称的方法吗?
例如,以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
对于 Dog 类,实现“Speak”的属性称为“Talk”。
如果我收到一个“对象”类型的狗对象,我可以这样做吗?
If TypeOf(object) Is ILifeForm Then
Dim str as string = CType(object, ILifeForm).GetUnderLyingPropertyName("Speak"))
' str now contains "Talk"
End If
【问题讨论】:
-
你为什么要把实现你的接口方法的方法命名为别的?从设计的角度来看,这很糟糕。
-
@Tejs 我什至没有意识到 vb.net 会允许这种情况发生......
-
是的,我也没有。目前正在阅读相关内容。我认为这源于他们能够确定与 C# 相比显式接口实现的含义
-
不管怎样,@Trucker_Jim,如果您尝试做这样的事情,界面可能不是您想要的。你到底想完成什么?
-
我试图减轻底层属性名称不必镜像接口属性名称这一事实。我创建了一个带有名为 TextToMerge 的属性的 IMailMergeable 接口。当一个对象被提供给我的 web 控件时,它会使用属性的显示名称填充其控件标签。如果对象是 IMailMergable,则会出现一个合并字段列表,并要求用户突出显示它们并将它们拖到页面上的 TextToMerge 字段。但是,TextToMerge 属性可能被称为“消息”,这会使用户感到困惑。