VB.NET中FillElements函数返回StructElements数组类型不匹配问题修复
Got it, let's resolve this type mismatch error without overhauling your code (no List required). The root problem is your FillElements function is declared to return a single StructElements object, but you're trying to return an array of that structure. Here's the step-by-step fix:
Step 1: Update the Function's Return Type in Gen Class
First, change the return type of FillElements from StructElements to StructElements() (an array of your structure):
Public Function FillElements(_param As String, count As Integer) As StructElements()
Step 2: Adjust Array Handling in the Function
Your existing Scopes case already creates an array, but we need to ensure all code paths return an array (even empty for other cases). Here's the updated code for the Gen class:
Public Structure StructElements Public ID As Integer Public Name As String End Structure Public Function FillElements(_param As String, count As Integer) As StructElements() Dim i As Integer = 0 Dim myConn As SqlConnection = New SqlConnection Dim myCmd As SqlCommand Dim myReader As SqlDataReader myConn.ConnectionString = sc.ConfigurationManager.ConnectionStrings("sidConnectionString").ConnectionString myCmd = myConn.CreateCommand myCmd.CommandText = "SELECT * FROM " & _param Select Case _param Case "Scopes" ' Create array with the specified size (matches your original logic) Dim Scope(count) As StructElements myConn.Open() myReader = myCmd.ExecuteReader() While myReader.Read AndAlso i <= count Scope(i).ID = myReader.Item(0) Scope(i).Name = myReader.Item(1).ToString i += 1 End While myReader.Close() myCmd.Dispose() myConn.Close() myConn.Dispose() ' Return the array directly now that the function type matches Return Scope ' Add other cases here, make sure each returns a StructElements() array ' Example for a default case: Case Else ' Return an empty array if no match to avoid null reference issues Return New StructElements() {} End Select End Function
Note: I added a check AndAlso i <= count in the While loop to prevent index out-of-bounds errors if the query returns more rows than your count parameter allows.
Step 3: Verify the edit.aspx Backend Code
Your existing backend code already declares Scope as an array, so no changes are needed here! The line:
Scope = istGen.FillElements("Scopes", iScopes)
Now works perfectly because the function returns the same array type that Scope is declared as.
Quick Notes
- Ensure all
Caseblocks inFillElementsreturn aStructElements()array (even empty ones) to avoid compile errors. - If you want to trim unused array slots (in case the query returns fewer rows than
count), you could useReDim Preserve Scope(i-1)before returning, but that's optional if you don't mind unused slots.
内容的提问来源于stack exchange,提问作者Luca S.

