【发布时间】:2012-12-10 01:51:09
【问题描述】:
我有一个通用类Command(Of T)
命令(部分)定义为:
Public Class Command(Of T As BaseType)
Inherits Command
Public Property Condition As Func(Of T, Boolean)
End Class
我想创建一个所有命令的列表,然后当我收到一个对象A 时,拉出与我的A 具有相同泛型类型的所有命令,对Condition(A) 的调用返回true
我可以的
Dim B As List(Of BaseType)
B.Add(New DerivedType)
但是
Dim C As New List(Of Command(Of BaseType))
C.Add(New Command(Of DerivedType))
引发转换错误。
我可以让Command 继承自非泛型对象(我们称之为CommandBase...)
Dim C As New List(Of CommandBase)
C.Add(New Command(Of DerivedType))
这可行,但现在我无法回到特定于类型的参考。这得到了正确的命令对象:
Dim CommandsOfTypeA = B.Where(function(x) x.GetType.GetGenericArguments(0).FullName = A.GetType.FullName)
但我现在不知道该怎么做...
Dim MatchingCommands = CommandsOfTypeA.Where(function(x) c.Condition(A))
因为 CommandsOfTypeA 是 List(Of Command) 而不是 List(Of Command(Of DerivedType))
我错过了什么?
【问题讨论】:
-
@MattBall 谢谢,我显然有点累了
标签: .net vb.net oop generics polymorphism