2011-02-07 123 views
0

我想声明一个属性作为一个接口的接口集合,我想稍后在构造函数中实例化显式类型。像这样的东西。属性和接口

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的目的。列表1[NtnAgent.LicenseFileDataNode]' can't be converted to an object of the type 'System.Collections.Generic.IList 1 [NtnAgent.IRCANFileDataNode]'。

总之,t他的问题是“为什么它不工作”?这是一个简化的方案,但很容易采取一个工作周期,但我需要了解原因,因为它失败了。

谢谢!

回答

1

让我们更简单地推理一下。假设IAnimal是您的界面,并且Animal是实现IAnimal的具体类型。那么,List<Animal>不是IList<IAnimal>。为什么?因为List<Animal>可以接受Animal的实例,并且IList<IAnimal>可以接受实现IAnimal的对象。试想一下:

class Animal : IAnimal { } 
class EvilAnimal : IAnimal { } 

因此,如果我们可以的List<Animal>一个实例分配给IList<IAnimal>类型的变量,可以插入EvilAnimal s转换你的List<Animal>,这显然是荒谬的,因为EvilAnimal不是Animal

+0

+1。为了进一步研究,Google协方差和逆变。 – StriplingWarrior 2011-02-07 16:46:00

1
> "Why It Didn't work"? 

由于IList(Of ILicenseFileDataNode) 元素类型是从List(Of LicenseFileDataNode)

例的元素类型diffenrent:如果LicenseFileDataNodeLicenseFileDataNodeMock都实现ILicenseFileDataNode

然后既可以添加到IList(Of ILicenseFileDataNode)List(Of LicenseFileDataNode)不能 包含LicenseFileDataNodeMock项目。

使用List(Of ILicenseFileDataNode)应该按预期工作。

更多详情请参阅Covariance and Contravariance in Generics