NullReference Exception to an objet that I initialized as New List(Of)?

一曲冷凌霜 提交于 2020-01-06 19:59:35

问题


Could someone explain why I obtain a NullReference Exception to an objet that I initialized as New List(Of)??

Module Module1
  ' MAIN =================================    
  Sub Main()
    Console.Clear()
    Console.WriteLine("Creating Bar")
    Dim myBar As New Bar()
    Console.ReadLine()
  End Sub    
End Module

Class Foo
  Public Overridable Property Test As String

  Public Sub New()
    Me.Test = "hello"
  End Sub
End Class

Class Bar
  Inherits Foo
  Private _MyString As New List(Of String)

  Public Sub New()
    MyBase.New()
  End Sub

  Public Overrides Property Test As String
    Get
      Return MyBase.Test
    End Get
    Set(value As String)
      MyBase.Test = value
      ' NULL REFERENCE EXCEPTION ???????!!!!!!!!!!!
      Console.WriteLine("{0}, and _MyString.Count = {1}", MyBase.Test, Me._MyString.Count)
    End Set
  End Property
End Class

回答1:


Foo.New() runs before the field initializers in Bar().

The New part of As New List(Of String) is actually part of the Bar.New() constructor, which runs after MyBase.New().



来源:https://stackoverflow.com/questions/12585555/nullreference-exception-to-an-objet-that-i-initialized-as-new-listof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!