无法将派生类型隐式转换为其基类泛型类型 -

时间:2016-07-13 10:26:00

标签: .net vb.net generics properties

我在下面使用泛型

Public Class ActionResult(Of T)

Private mResultInfo As T
Public Property ResultInfo() As T
    Get
        Return mResultInfo
    End Get
    Set(ByVal value As T)
        mResultInfo = value
    End Set
End Property
End Class



Public Class AnalysisResult
   Public Property ResultFileName As String
   Public Property ResultValue As String
End Class


Public Class TestAnalysisResult
  Inherits AnalysisResult
  Public Property Score As Long
End Class

Public Function PerformAnalysis(analysisParameters As AnalysisParameters) As ActionResult(Of AnalysisResult)
  Dim actionResult As New ActionResult(Of TestAnalysisResult)
  Return actionResult ' Causing me compile time error. Cannot implicitly convert derived type to its base generic type
End Function

我相信派生类可以是基类的种姓。 但不知何故上面的事情是行不通的。我用Google搜索并且似乎与协方差有关?
有人可以在这里说些什么吗? 谢谢。

1 个答案:

答案 0 :(得分:0)

但我认为你最好使用通用的返回值。像这样:

Public Function PerformAnalysis(Of T)(analysisParameters As AnalysisParameters) As ActionResult(Of T)
    Dim actionResult As New ActionResult(Of T)
    Return actionResult
End Function