我正在努力理解数组并阅读这个主题,但是当你刚刚开始编程并且没有人可以要求解释时,大部分文献都不容易理解.这是我的二维数组:
'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岁的孩子交谈,或者是一个可能帮助我理解这个问题的网站.谢谢
关键在于数据是相关的.Class 不是将你的"汽车"拆分成碎片存储在不同的数组中,而是允许你创建一个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
)来管理它们存储的数据,以便与该类相关的所有与Car或Employee或Order相关的内容.
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)
A List(Of T)
可以用作DataSource
某些控件:
myDGV.DataSource = Cars
在DataGridView将为每个创建一个列属性的Car
类,并添加一行列表中的每个汽车对象-简单!
要么:
myListBox.DataSource myList.DisplayMember = "Make" myList.ValueMember = "Id"
用户将Make
在ListBox(或您定义的任何内容)中看到. SelectedValue
将是他们选择的汽车对象的Id,SelectedItem
并将成为整个汽车对象.无需通过不同的数组来搜索相关数据 - 它总是在一个地方.