我终于找到了解决这个问题的办法。从 tcarvin 的建议开始,我改变了一些事情并得到了这个解决方案:
我制作了一个单独的辅助类,带有一个共享字典:
Private Shared _QuestionStyles As New Dictionary(Of Type, Func(Of Byte(), QuestionBase)) From {
{GetType(QuestionStyleOne), Function(questionBinary)
Return Deserialize(Of QuestionStyleOne)(questionBinary)
End Function},
{GetType(QuestionStyleTwo), Function(questionBinary)
Return Deserialize(Of QuestionStyleTwo)(questionBinary)
End Function}
}
在同一个类中,我创建了一个方法来尝试检索以纠正存储在字典中的函数:
Public Shared Function DoDeserializeQuestion(ByVal questionType As Type, ByVal questionBinary As Byte())
Dim deserializeQuestion As Func(Of Byte(), QuestionBase) = Nothing
If (_QuestionStyles.TryGetValue(questionType, deserializeQuestion)) Then
Return deserializeQuestion(questionBinary)
Else
Throw New ArgumentException("QuestionType not known")
End If
End Function
现在我只需要调用这个:
Using reader As IDataReader = GetQuestions(id)
While (reader.Read)
collection.Add(QuestionTypeHelper.DoDeserializeQuestion(question.GetType, CType(reader.Item(DataFields.Question), Byte())))
End While
End Using
这让我从数据库中得到正确的问题,反序列化该二进制文件并将它们转换为适当的问题类型。在其他情况下以及需要这种类型的铸造时非常可重用。