我正在努力理解数组并阅读这个主题,但是当你只是刚刚开始编程并且没有人可以的时候,大部分文献都不容易理解。请解释一下。这是我的二维数组:
'Declare 2-diensional array of Strings
Dim cars(,) As String =
New String(,) {{"BMW", "Coupe", "Reg:2015", "5 Door"},
{"Ford", "Focus", "Reg:2015", "3 Door"},
{"Land Rover", "Discovery", "Reg:2014", "5 Door"},
{"Vauxhall", "Astra", "Reg:2014", "3 Door"},
{"SEAT", "Ibiza", "Reg:2013", "5 Door"}}
' Get bounds of the array.
Dim bound0 As Integer = cars.GetUpperBound(0)
Dim bound1 As Integer = cars.GetUpperBound(1)
' Loop over all elements.
For i As Integer = 0 To bound0
For x As Integer = 0 To bound1
' Get element.
Dim s1 As String = cars(i, x)
Console.ForegroundColor = ConsoleColor.Green
Console.Write(s1 & ", ")
Next
Console.WriteLine()
Next
Console.ReadKey()
Console.WriteLine("Please enter the name of the record you wish to view")
Dim s = Console.ReadLine()
Dim value As String = Array.Find(cars, Function(x) (x.StartsWith(s)))
Console.WriteLine(value)
Console.ReadKey()
这是引起问题的行
Dim value As String = Array.Find(cars, Function(x) (x.StartsWith(s)))
Visual Studio建议错误是因为"无法从这些参数推断出类型参数的数据类型。明确指定数据类型可能会纠正此错误。" 我无法理解这个错误意味着什么。请有人请解释一下,好像和一个10岁的孩子交谈,或者是一个可能帮助我理解这个问题的网站。感谢
答案 0 :(得分:9)
关键在于数据与相关。而不是将您的“汽车”拆分为多个部分以存储在不同的数组中,而是允许您创建一个Car
对象,并将各种汽车存储在已键入的List
中:
Classes
和Lists
Public Class Car
Public Property Id As Int32
Public Property Make As String
Public Property Model As String
Public Property Year As Int32
'... etc
End Class
现在你有一个容器来保存一辆车的所有信息。这就像Car
对象的外观蓝图。类还可以包含方法(Sub
或Function
)来管理它们存储的数据,以便可以由该类管理与汽车或员工或订单相关的所有内容。
Dim c As New Car ' create a new car object
c.Make = "Mazda"
c.Model = "Miata"
c.Year = 2013
或者在声明时初始化:
Dim c As New Car With {.Make = "Mazda", .Model = "Miata" ...}
现在,新千年版的数组是List
。这些更容易可以使用,因为它们可以自行调整大小:
Dim Cars As New List(Of Car)
Cars
集合只能 存储汽车对象,它存储的每辆汽车都会将数据保存在一起。还有许多其他集合类型,例如Dictionary
,您最终会想要熟悉它们。将马自达添加到列表中:
' c is the car object created above
Cars.Add(c)
与数组不同,您无需知道将要使用多少辆汽车,因为它们会自行调整大小。要引用一个,Cars(n)
将引用一个汽车对象:
' n is the index of a car in the list
Dim str = Cars(n).Make & " is " & Cars(n).Color
使用临时Car
变量迭代列表:
For Each c As Car In Cars
' c will be Cars(0), Cars(1) etc as we step thru
Console.WriteLine("Index {0} is a BEAUTIFUL {1} {2}",
Cars.IndexOf(c), c.Year, c.Model)
' e.g
' "Index 4 is a BEAUTIFUL 2015 Camry"
Next
找一个或第一个:
Dim myCar = Cars.FirstOrDefault(Function (f) f.Make = "Mazda" AndAlso f.Year = 2013)
对于某些控件,List(Of T)
可用作DataSource
:
myDGV.DataSource = Cars
DataGridView将为Car
类中的每个 Property 创建一个列,并为列表中的每个car对象添加一行 - 简单!
或者:
myListBox.DataSource
myList.DisplayMember = "Make"
myList.ValueMember = "Id"
用户将在ListBox中看到Make
(或您定义的任何内容)。 SelectedValue
将是他们选择的汽车对象的ID,SelectedItem
将是整个汽车对象。无需通过不同的阵列进行膛线查找相关数据 - 它总是在一个地方。