处理接口时如何处理共享成员? [英] How do you handle shared members when dealing with interfaces?
问题描述
因此,我做了很多工作,试图为一组通用的类建立接口。想法是创建一个每个类都可以在集合中使用的接口,但最终每个类都是不同的。原来接口不喜欢共享成员。我尝试过的操作:
So I did tons and tons of work trying to make an interface for a common set of classes. The idea was to make an interface that each class could use within the set, but ultimately each class is different. Turns out interfaces do not like shared members. What I tried:
Public Interface ISomeInterface
Shared Property Meta() as Object
End Interface
Public Class A
Implements ISomeInterface
Shared Public Property Meta() as Object Implements ISomeInterFace.Meta
'Set/get methods
End Propery
Public Function Haduken() as Object
'perform Haduken
End Function
End Class
Public Class B
Implements ISomeInterface
Shared Public Property Meta() as Object Implements ISomeInterFace.Meta
'Set/get methods
End Propery
Public Function SonicBoom() as Object
'perform sonic boom
End Function
End Class
很显然,如果我完成了此作业,我会知道共享成员不能在接口中使用。我是否应该让各个类完全负责处理其共享成员?还有另一种方法可以将共享成员的耦合降低到最低限度吗?大约有20个左右的类将实现一个接口。
Obviously, had I done my homework on this, I would have known that shared members can't be use in interfaces. Should I just leave the individual classes completely responsible for handling its shared members? Is there another way to keep coupling down to a minimum with shared members? Theres about 20 something or so classes that will implement a single interface. Thanks in advance.
推荐答案
解决此问题的最简单方法是拥有 Private
接口的实现,该接口仅转发给 Shared
成员
The simplest way to work around this is to have a Private
implementation of the interface which simply forwards to the Shared
member
Public Shared Property Meta As Object
' Get / Set methods
End Property
Private Property MetaImpl() as Object Implements ISomeInterFace.Meta
Get
return Meta
End Get
Set
Meta = Value
End Set
End Propery
此模式可让您维护相同的面向公众的API并仍实现接口。
This pattern allows you to maintain the same public facing API and still implement the interface.
这篇关于处理接口时如何处理共享成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!