我的代码中存在问题。这是有问题的片段。读取该行确实有效,但在他应该用键和值填充zeilendict时,他会抛出一个“System.NullReferenceException”,我不知道为什么。
我在循环中做错了什么,或者字典是不正确的?或者arr1是空的吗?
Module Module1
Public zeilendict As Dictionary(Of String, Integer)
Public insertdict As Dictionary(Of String, String)
Public Sub einlesen()
Form1.ID = 0
Form1.OpenFileDialog1.ShowDialog()
Form1.path = Form1.OpenFileDialog1.FileName
Form1.OpenFileDialog1.Dispose()
Dim fs As FileStream = New FileStream(Form1.path, FileMode.Open, FileAccess.Read)
Dim sr As StreamReader = New StreamReader(fs)
Dim ersteZeile = sr.ReadLine()
Form1.arr1 = ersteZeile.Split(New Char() {";"c})
sr.Close()
fs.Close()
Dim i As Integer
For i = 0 To Form1.arr1.Length - 1
Form1.DataGridView1.Rows.Add(Form1.arr1(i))
Next
Dim i1 As Integer
For i1 = 0 To Form1.arr1.Length - 1
zeilendict.Add(Form1.arr1(i1), 0)
Next
答案 0 :(得分:1)
好像你没有发起你的字典。添加项目会产生NullRefException
尝试添加:
Public zeilendict As Dictionary(Of String, Integer) = new Dictionary(Of String, Integer)()
或将其设置为方法中的第一行:
zeilendict = new Dictionary(Of String, Integer)()
也为其他词典
执行此操作答案 1 :(得分:0)
在声明中添加关键字“新建”以初始化词典:
Public zeilendict As New Dictionary(Of String, Integer)
否则只会声明但不包含任何内容,因此当您尝试添加内容时会出现异常。
更多信息:http://msdn.microsoft.com/en-us/library/7zc73115%28v=vs.90%29.aspx