I have a Function that returns a struct in VB.NET:
Public Shared Function StoreData(Byval abc as store) as pcStruct
Dim st as new pcStruct
For each pc as pent in abc.route
st.stra.Add("test")
next
st.message="Successfully uploaded"
Return st
End Functi开发者_如何转开发on
Where as in my struct I have two variables:
- stra is an Arraylist
- message is a string
When I try to populate the structure as shown above, I get an a nullvalue exception. What am I doing wrong?
The st.stra
is not initialized
Try something like:
Dim arr as new ArrayList()
st.stra=arr
before you use st.stra.Add
Ngu's answer is most likely the problem.
Specifically, remember that Structures can have constructors. If you haven't written one for your pcStruct structure, you might want to consider it:
Public Structure pcStruct
Private thisMessage As String
Private thisList as ArrayList
Public Sub New()
thisList = New ArrayList()
End Sub
Public Property stra As ArrayList
Get
Return thisList
End Get
End Property
Public Property Message As String
Get
Return thisMessage
End Get
Set
thisMessage = Value
End Set
End Property
End Structure
Some argue that it's not necessary to do this in the constructor, but that you should simply do it where the member variable is declared. There's some evidence that this performs better, but I would argue that this will depend on how many of these objects you're declaring. If you're not declaring vast amounts of them, the performance benefit does not outweigh the clarity and extensibility benefit of placing your initialization code in one place. But, as must be pointed out, that is entirely my opinion and must be taken with both a grain of salt and an air freshener.
精彩评论