.net 定义从一个接口到另一个无关接口的隐式转换
我有两个接口.net 定义从一个接口到另一个无关接口的隐式转换,.net,vb.net,.net,Vb.net,我有两个接口IFoo和IBar,它们都继承自IBase。 如何定义缩小/扩大转换操作的等效项,以便隐式或显式地将IFoo转换为IBar 从实现的角度来看,在我的例子中,这样做没有问题,因为实现IFoo或IBar的所有对象的数据都完全依赖于实现IBase的基类,例如: Class Product Implements IProduct Protected Property IdentityNumber as Integer End Class Class Techn
IFoo
和IBar
,它们都继承自IBase
。
如何定义缩小
/扩大
转换操作的等效项,以便隐式或显式地将IFoo
转换为IBar
从实现的角度来看,在我的例子中,这样做没有问题,因为实现IFoo
或IBar
的所有对象的数据都完全依赖于实现IBase
的基类,例如:
Class Product
Implements IProduct
Protected Property IdentityNumber as Integer
End Class
Class TechnicalFile
Inherits Product
Implements ITechnicalFile
ReadOnly Property IdentityNumber as Integer Implements ITechnicalFile.IdentityNumber
Get
Return MyBase.IdentityNumber
End Get
End Property
End Class
Class SalesFile
Inherits Product
Implements ISalesFile
Private Property DataBase as New DataBaseAPI
Function GetBrand as String Implements ISalesFile.GetBrand
Dim MyProduct As IFile = DataBase.GetProductFile(Mybase.IdentityNumber)
Return MyProduct.Brand
End Function
End Class
通过以上示例,我希望能够做到:
Dim MyTechFile as ITechnicalFile = New TechnicalFile
Dim MySalesFile as ISalesFile = MyTechFile '<- ITechnicalFile would implement an implicit conversion to ISalesFile
Dim MyTechFile as itetechnicalfile=新TechnicalFile
Dim MySalesFile as ISalesFile=MyTechFile'如果它们都是ITechnicalFile
,您能否将它们作为接口传递,而不是在具体类型之间转换?强制转换的好处是什么?没有办法用隐式函数实现,但可以用成员函数实现。这种用法可能有点难看,因为您必须先创建然后转换,或者使用虚拟对象。我简化了这个问题,但在我的例子中,我处理的是协变类型的通用接口的树状图。长话短说,由于一些架构限制,我们最终需要从树形植物的一个分支转换到另一个分支。@Craig,这与我们目前正在做的很接近:我们注入了一个工厂,它实现了一个函数转换(obj作为IFoo)作为IBar
,但是这会污染大量的代码。顺便问一下,你说的虚拟对象到底是什么意思?