.net VB.1“类型的净值”;“类”;改为;“类型”;
我有这样一个界面:.net VB.1“类型的净值”;“类”;改为;“类型”;,.net,vb.net,.net,Vb.net,我有这样一个界面: Public Interface IDescriptionIdentityPair Property Id() As String Property Description() As String End Interface 我有一门课是这样的: Public Class DescriptionIdentityPair : Implements IDescriptionIdentityPair Public Property Id As Strin
Public Interface IDescriptionIdentityPair
Property Id() As String
Property Description() As String
End Interface
我有一门课是这样的:
Public Class DescriptionIdentityPair : Implements IDescriptionIdentityPair
Public Property Id As String Implements IDescriptionIdentityPair.Id
Public Property Description As String Implements IDescriptionIdentityPair.Description
Public Overrides Function ToString() As String
Return Description
End Function
End Class
我有这样一种方法:
Public Shared Function AddEmptyRow(Of T As IDescriptionIdentityPair)(ByVal collection As IList(Of T)) As IList(Of T)
Dim AddEmptyRowToCollection = collection
collection.Insert(0, New DescriptionIdentityPair With {.Id = "", .Description = FxApplication.DefaultText})
Return collection
End Function
在尝试插入DescriptionIdentityPair类的新实例时,我遇到了一个编译时错误,“DescriptionIdentityPair”类型的值无法转换为T。我甚至尝试将DescriptionIdentityPair强制转换到它的接口(在绝望中),但这并没有解决问题。错误是正确的。考虑另一个类实现接口的情况:
Public Class AnotherDescriptionIdentityPair : Implements IDescriptionIdentityPair
使用T=AnotherDescriptionIdentityPair
调用泛型方法:
Dim list As New List(Of AnotherDescriptionIdentityPair)
AddEmptyRow(list)
Public Shared Function AddEmptyRow(Of T As {New, IDescriptionIdentityPair})(ByVal collection As IList(Of T)) As IList(Of T)
Dim AddEmptyRowToCollection = collection
collection.Insert(0, New T With {.Id = "", .Description = "DefaultDescription"})
Return collection
End Function
当您尝试将DescriptionIdentityPair
的实例添加到列表(另一个DescriptionIdentityPair的)
时会发生什么情况
您可以修复方法的附加New
泛型约束,并初始化New T
,而不是New DescriptionIdentityPair
:
Dim list As New List(Of AnotherDescriptionIdentityPair)
AddEmptyRow(list)
Public Shared Function AddEmptyRow(Of T As {New, IDescriptionIdentityPair})(ByVal collection As IList(Of T)) As IList(Of T)
Dim AddEmptyRowToCollection = collection
collection.Insert(0, New T With {.Id = "", .Description = "DefaultDescription"})
Return collection
End Function
为什么要返回列表?任何调用
AddEmptyRow
方法的代码显然已经有了对列表的引用。@Stevendogart使方法链接成为可能吗?@MarcinJuraszek是的,我认为这是唯一有效的原因。我只是怀疑这可能根本不是什么好理由。但你在下面的评论中解决了我的主要问题;我不知道IList不是协变的(除非它有一个get索引器)!我可以删除泛型约束,现在只使用IEnumerable(IdeDescriptionIdentityPair的)作为参数type@contactmatt但您将无法将项目添加到IEnumerable
,因为它是只读集合接口!您只能使用新元素和所有源元素返回新的IEnumerable
,例如使用Concat
扩展方法。它似乎是通过将IEnumerable参数转换为列表,然后在其中插入一项来工作的。是,只要您不提供实现您的接口的不同类的列表
,这应该是可行的。否则将出现运行时转换异常。我劝你不要走这条路。为什么不按照我的答案添加New
generic constraint?@contactmatt由于同样的问题,您不能使用此技巧-列表不是协变的。