[英]Why can't I recast my concrete type as an interface
I am looking to implement the ability to compare and sort classes in my model. 我希望实现在模型中对类进行比较和排序的功能。 All of the objects in my model will need some common functionality regarding to comparisons so I created an abstract BaseComparer
that implements IComparer
. 我的模型中的所有对象都需要一些与比较有关的通用功能,因此我创建了一个实现IComparer
的抽象BaseComparer
。
Public MustInherit Class BaseComparer(Of T)
Implements IComparer(Of T)
End Class
Each class in the model has its own concrete implementation of BaseComparer
. 模型中的每个类都有其自己的BaseComparer
具体实现。
Public Class PersonComparer
Inherits BaseComparer(Of Person)
End Class
Then I have a ComparerFactory
that is responsible for creating and initializing the comparers: 然后,我有一个ComparerFactory
,它负责创建和初始化比较器:
Public Class ComparerFactory
Public Shared Function GetComparer(ByVal target As Type) As IComparer
If target Is GetType(Person) Then
Return New PersonComparer()
ElseIf target Is GetType(Organization) Then
Return New OrganizationComparer()
ElseIf 'etc...
End If
End Function
End Class
The problem is that ComparerFactory.GetComparer
throws following error . 问题是ComparerFactory.GetComparer
引发以下错误 。 Interestingly enough, the code compiles fine, but it only errors at runtime. 有趣的是,代码可以很好地编译,但是它只会在运行时出错。
Unable to cast object of type 'PersonComparer' to type 'System.Collections.IComparer'. 无法将类型为“ PersonComparer”的对象转换为类型为“ System.Collections.IComparer”的对象。
PersonComparer
inherits from BaseComparer
which implements IComparer
. PersonComparer
继承自实现IComparer
BaseComparer
。 What am I missing here? 我在这里想念什么? Why can't it be cast? 为什么不能投射? I suspect it has something to do with IComparer(Of T)
我怀疑这与IComparer(Of T)
Your abstract class implements the generic interface IComparer(Of T)
, but not the non-generic interface IComparer
. 您的抽象类实现了通用接口IComparer(Of T)
,但没有实现非通用接口 IComparer
。 These are actually two different interfaces, which are not related to each other, not even by inheritance. 实际上,它们是两个不同的接口,它们甚至通过继承也不相互关联。
You can simply have your abstract class implement both interfaces: 您可以简单地让您的抽象类实现两个接口:
Public MustInherit Class BaseComparer(Of T)
Implements IComparer(Of T), IComparer
End Class
There are two different interfaces: 有两种不同的接口:
IComparer (http://msdn.microsoft.com/en-us/library/system.collections.icomparer.aspx)
and 和
IComparer<T> (http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx)
The latter generic interface does not inherit from the former. 后者的通用接口不会从前者继承。
I would suggest making your BaseComparer directly implement the non-generic IComparer as well. 我建议您也让BaseComparer直接实现非通用IComparer。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.