.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.List
1[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:A
List
也不是
List
。您可以将
EvilAnimal
添加到
List
。映射
T->List
T
@Jason中不是协变的,你改变了OP的主要问题,OP有List没有List,我是这么说的。公共属性集合为IList(ILicenseFileDataNode的)