使用List(of)内部结构 [英] using List(of) inside structure

查看:128
本文介绍了使用List(of)内部结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

am使用
出现错误

am getting an error using

Structure JobItem
       Dim Index As Integer
       Dim Url As String
       Dim Status As String
       Dim WorkData As String
       Dim ListUrls As List(Of Uri)
   End Structure



当我尝试添加到像这样的ListUrls时



when i try to add to ListUrls like this

Dim jb As New JobItem
jb.ListUrls.Add(urlNext)



我收到错误Object reference not set to an instance of an object.

我该如何解决?



i get an error Object reference not set to an instance of an object.

how do i fix this?

推荐答案

就是这样:您没有实例化引用类型对象之一,所以其中一个是null,或一些明确地将null分配给该变量的代码.在您的情况下,这是未初始化的ListUrls.构造结构后,它为null.使用New创建一个列表.在结构中添加一个构造函数并初始化所有内容.您应该使用带有参数Index,UrlStatusWorkData的构造函数.

使用字符串类型不合适. Status可能是枚举,Url必须是Url类型;我不知道WorkData是什么,为什么,但是不太可能是字符串类型.

—SA
This is what it is: you did not instantiate one of the reference-type objects, so one of them is null, or some code explicitly assigned null to the variable. In your case, this is uninitialized ListUrls. After you constructed the structure, it''s null. Use New to create a list. Add a constructor to the structure and initialize everything. You should use a constructor with parameters Index, Url, Status, and WorkData.

Using string types in inappropriate. Status is likely to be enumeration, Url must be of Url type; I don''t know what''s WorkData and why, but also unlikely the string type.

—SA


如果需要代码,可以在这里找到,但是请阅读SAKryukov关于错误原因的出色解释.

If you want the code, well here it is but do read SAKryukov''s excellent explanation on why there is an error.

Dim jb As New JobItem
Dim newList As New List(Of Uri)
newList.Add(New Uri("some path", UriKind.RelativeOrAbsolute))
jb.ListUrls = newList



现在应该可以使用.



It should work now.


这不是您问题的真正答案,但我想指出一点.使用结构通常不是最好的方法.上课是大约99.99%的时间里上课的最佳方式.
请在此处使用结构时阅读 [
Not really an answer to your question, but something I want to point out. Using a Structure is usually not the best way to go. Classes are the best way to go in probably 99,99% of the time.
Read here when to use Structures[^].
I think by using the List(Of T) you pretty much break those rules.
I am not saying that using a Structure is plain wrong (you probably have your reasons) I just want to point out that maybe you could go for a Class instead.
Also taken the arguments of SAKryukov you probably need to make Status an Enum, Url an Url Class etc. By creating a Class you will have more flexibility and you will be sure everything is ok in the future.


这篇关于使用List(of)内部结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆