Null 检查始终返回 null,如果删除则返回未设置为对象实例的对象引用
我有一些代码通过 GetChildren 函数获取菜单的子项,该函数采用 menuData 列表:
Dim builtMenu As New List(Of MenuData)(_rawData.FindAll(Function(item) item.GroupingID = 0))
For Each menuData As MenuData In builtMenu
If menuData.Children IsNot Nothing Then
menuData.Children.AddRange(GetChildren(menuData))
End If
Next
如果我检查 menudata.children 是否不是什么,它总是什么都不是,因为 GetChildren 函数尚未运行(提供子项,确实存在)。如果我删除此检查并只有此代码:
Dim builtMenu As New List(Of MenuData)(_rawData.FindAll(Function(item) item.GroupingID = 0))
For Each menuData As MenuData In builtMenu
menuData.Children.AddRange(GetChildren(menuData))
Next
然后我会在 menuData.Children.AddRange(GetChildren(menuData)) 上看到一个对象引用未设置为对象实例错误,
请告诉我如何解决此问题问题? 多谢
I have some code which gets child items for a menu via the GetChildren function which takes a list of menuData:
Dim builtMenu As New List(Of MenuData)(_rawData.FindAll(Function(item) item.GroupingID = 0))
For Each menuData As MenuData In builtMenu
If menuData.Children IsNot Nothing Then
menuData.Children.AddRange(GetChildren(menuData))
End If
Next
If I check if menudata.children isnot nothing, it always is nothing because the GetChildren function is yet to run (providing the child items, which do exist). If I remove this check and just have this code:
Dim builtMenu As New List(Of MenuData)(_rawData.FindAll(Function(item) item.GroupingID = 0))
For Each menuData As MenuData In builtMenu
menuData.Children.AddRange(GetChildren(menuData))
Next
Then I am presented with a Object reference not set to an instance of an object error on menuData.Children.AddRange(GetChildren(menuData))
Please can you tell me how I get around this problem?
Thanks a lot
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
menuData.Children
从未被实例化,因此它是一个 null (Nothing
) 引用。使用之前需要先实例化它:
Your
menuData.Children
has never been instantiated, so it is a null (Nothing
) reference.You need to instantiate it before you use it: