我希望将通用字典作为vb.net中函数的返回值。
我怎么能得到这个?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim buttons As Dictionary(Of Integer, Button) = generateControls(Of Button)(3)
Dim textBoxes As Dictionary(Of Integer, TextBox) = generateControls(Of TextBox)(3)
End Sub
Private Function generateControls(Of T)(repeat As Integer) As Dictionary(Of Integer, T)
Dim dic As New Dictionary(Of Integer, T)
For i As Integer = 0 To repeat - 1
Dim control As New T
dic.Add(i, control)
Next
Return dic
End Function
答案 0 :(得分:2)
您需要指定一个类型约束,声明该类型具有默认构造函数。
使用generateControls(Of T As New)
代替generateControls(Of T)
但我更喜欢:
Dim result = Enumerable.Range(0, 3).
ToDictionary(Function(i) i, Function(i) New TextBox() With {... })