.net 属性和接口
我希望将属性声明为接口的接口集合,并希望稍后在构造函数中实例化显式类型。像这样的.net 属性和接口,.net,vb.net,.net,Vb.net,我希望将属性声明为接口的接口集合,并希望稍后在构造函数中实例化显式类型。像这样的 Public Class LicenseFile Implements ILicenseFile Public Property Collection As IList(Of ILicenseFileDataNode) Public Sub New() Collection = New List(Of LicenseFileDataNode) 'here throws a
Public Class LicenseFile
Implements ILicenseFile
Public Property Collection As IList(Of ILicenseFileDataNode)
Public Sub New()
Collection = New List(Of LicenseFileDataNode) 'here throws an exception.
End Sub
End Class
当然,LicenseFileDataNode实现了ILicenseFileDataNode
构造函数的唯一行启动一个异常,如下所示:
“类型的对象
'System.Collections.Generic.List1[NtnAgent.LicenseFileDataNode]'
无法转换为该类型的对象
'System.Collections.Generic.IList
1[NtnAgent.ILicenseFileDataNode]'
简言之,问题是“为什么它不起作用”?这是一个简化的场景,但很容易采取行动,但我需要理解原因,因为它失败了
谢谢!让我们简化推理。比如说,
IAnimal
是你的界面,Animal
是你实现IAnimal
的具体类型。List
不是IList
。为什么?因为List
可以接受Animal
和IList
的实例接受实现IAnimal的对象。请考虑:
class Animal : IAnimal { }
class EvilAnimal : IAnimal { }
因此,如果我们可以将List
的一个实例分配给IList
类型的变量,您可以将EvilAnimal
s插入List
,这显然是荒谬的,因为EvilAnimal
不是动物
> "Why It Didn't work"?
因为IList的元素类型(ILicenseFileDataNode的)
与(LicenseFileDataNode的)列表的元素类型不同
示例:如果LicenseFileDataNode
和LicenseFileDataNodeMock
都实现ILicenseFileDataNode
然后两者都可以添加到IList(ILicenseFileDataNode的)
,但是列表(LicenseFileDataNode的)
不能
包含LicenseFileDataNodeMock
项
使用列表(ILicenseFileDataNode)
应该可以正常工作
有关更多详细信息,请参见+1。为了进一步研究,谷歌搜索协方差和逆变。列表是列表而不是列表,您可以将EvilAnimal添加到此列表中。@Saeed:AList
也不是List
。您可以将EvilAnimal
添加到List
。映射T->List
在T
@Jason中不是协变的,你改变了OP的主要问题,OP有List没有List,我是这么说的。公共属性集合为IList(ILicenseFileDataNode的)