【问题标题】:VB.net Structures and ListsVB.net 结构和列表
【发布时间】:2013-09-21 05:39:04
【问题描述】:

假设我有一个结构

Structure Test
    Public Names as List(Of Strings)
End Structure

我收到错误

A first chance exception of type 'System.NullReferenceException' occurred

所以我进入了代码,每次向名称添加字符串时都会出错

例子:

Dim a as new Test
Dim b = 1
While b < 2
    if b = 1 then
        a.add("Cheese")
    End If
    b += 1
End While

a.add("Cheese") 会抛出错误

有什么想法吗?

【问题讨论】:

    标签: vb.net structure runtime-error


    【解决方案1】:

    您需要一个新的List 才能调用.Add 方法;此外,您正在对新结构而不是其 List 成员调用 add 方法。

    Dim a as new Test
    a.Names = New List(Of String)
    Dim b = 1
    While b < 2
        if b = 1 then
            a.Names.Add("Cheese")
        End If
        b += 1
    End While
    

    【讨论】:

      【解决方案2】:
      Structure Test
          Public Sub New()
             Me.Names = New List(Of String)
          End Sub 
          Public Names as List(Of Strings) 
      End Structure
      

      如果所需的行为是当您新建结构时,您可以在构造函数中初始化名称列表,您可以开始将项目添加到列表中。

      http://msdn.microsoft.com/en-us/library/2hkbth2a(v=vs.80).aspx/css

      【讨论】:

        【解决方案3】:
        Public Names As New List(Of String)
        

        或者

        Public Names As List(Of String)
        ..
        Names = New List(Of String)
        

        到目前为止,您所做的只是声明 Names 将是一个字符串列表,如果并且当您开始创建它的实例时……您从未这样做过。也是String 不是Strings

        【讨论】:

        • 通常结构会负责更新列表
        • 我尝试了第一个选项,将 Public Names As New List(Of String) 我收到错误 A non shared member in a structure can not be declared New On the second part Names = New List(Of String )我会用我的例子把它放在哪里
        猜你喜欢
        • 1970-01-01
        • 2013-01-03
        • 1970-01-01
        • 2018-04-14
        • 1970-01-01
        • 2019-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多