需要帮助在VB.Net中初始化通用属性

时间:2014-10-07 19:16:46

标签: vb.net generics nullreferenceexception

我创建了一个请求类。这是它的缩写版本:

Public Class Request(Of T)
    Private _Account As String
    Public Property Account() As String
        Get
            Return _Account
        End Get
        Set(ByVal value As String)
            _Account = value
        End Set
    End Property
    Private _InnerRequest As T
    Public Property InnerRequest() As T
        Get
            Return Me._InnerRequest
        End Get
        Set(ByVal value As T)
            Me._InnerRequest = value
        End Set
    End Property
End Class

然后我还有另外两个我打算用这个类 - 再次缩写

Public Class Individual
    Public FirstName As String
    Public LastName As String
    Friend Sub New()
    End Sub
End Class

并且

Public Class Commercial
    Public EntityName As String
    Friend Sub New()
    End Sub
End Class

同样,这两个都很简短。当我尝试使用个人或商业的属性时,问题出现了:

Dim Req As New Request(Of Individual)()
Req.InnerRequest.FirstName = "Herman"  <-- Null Ref Exception

那么......我如何得到我的内部请求null ref异常踢?我尝试在Request的New子句中使用Me._InnerRequest = New T,但没有骰子。有办法解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

必须先将Req.InnerRequest设置为Individual的对象实例。

Req.InnerRequest = new Individual()
Req.InnerRequest.FirstName = "Herman"

或者通过以下修改为InnerRequest创建实例

Public Class Request(Of T As {New}) 'Classes of type T must have a public new constructor defined
::
Private _InnerRequest As New T() 'Creates a new class of type T when an instance is created of Request

并使其他类Public的构造函数而不是Friend

比你可以直接做的

Dim Req As New Request(Of Individual)()
Req.InnerRequest.FirstName = "Herman"

答案 1 :(得分:2)

@Barry已经回答了主要问题,但如果您更喜欢对象初始化器,那么这里有另一种语法:

Req.InnerRequest = new Individual() With { FirstName = "Herman" }

或者,如果您愿意,可以重载Individual类的构造函数:

Dim individual As New Individual("Herman")
Req.InnerRequest = individual

Individual类看起来像:

Public Class Individual
    Public FirstName As String
    Public LastName As String

    Friend Sub New()
    End Sub

    Friend Sub New(firstName As String)
        Me.FirstName = firstName
    End Sub

End Class

答案 2 :(得分:2)

您可能应该考虑将T限制为某个Entity类:

Public Class Request(Of T As Entity)

个人和商业都将继承:

Public Class Individual : Inherits Entity

然后可以在此Entity类(可以是abstract / MustInherit)上声明一个可覆盖的属性Name类型的String,这应该提供一些灵活性。否则你将很难消耗你的设计模式。