我有一个创建Customer对象的类,它将存储在Dictionary中。字典使用(Of TInteger,Customer)。 添加新客户时需要具有用户可用于搜索客户的唯一ID。我打算使用Dictionary Key作为ID。
当我的addCustomer表单单击addCustomer按钮时。它创建了客户对象。然后将该对象放入字典值。通过调用Customer类中的函数来设置键,该函数创建并设置静态变量。然后加1并返回。
这是我的客户类(减去帮助不需要的代码)
Public Class Customers
'Create a dictionary to hold the new customer
Friend customerDict As New Dictionary(Of Integer, Customers)
Private cFirstName As String 'first name
Private cLastName As String 'last name
Private cAddress As String 'field to address
Private cContactInfo As String 'contact information i.e. a telephone number Or an e-mail address
Private cCountry As Boolean 'country the customer lives In
Friend cMortgage As List(Of Mortgage) 'customer has one or more mortgages
Public Sub New(cFirstName1 As String, cLastName1 As String, cAddress1 As String, cContactInfo1 As String, cCountry1 As Boolean)
Me.CFirstName1 = cFirstName1
Me.CLastName1 = cLastName1
Me.CAddress1 = cAddress1
Me.CContactInfo1 = cContactInfo1
Me.CCountry1 = cCountry1
cMortgage = addCMortgage()
End Sub
......
Code for getters and setters
......
'Function to create a new customer ID/Key
Public Function getCustomerID() As Integer
'Create variable that adds 1 everytime a customer is created. Then use that as customer Id and as the Customer Dictionary Key.
Static cIdKey As Integer = 0
cIdKey += 1
Return cIdKey
End Function
End Class
这是我的addCustomerForm代码,它创建对象并调用函数并设置字典。
Public Class frmAddNewCustomer
Private Sub frmAddNewCustomer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnAddMortgage_Click(sender As Object, e As EventArgs) Handles btnAddMortgage.Click
Dim cCountry As Boolean
Dim cAddress As String
......'Set up address format and code validation.....
'Create the Customer object
Dim Customers As New Customers(txtfName.ToString, txtLName.ToString, cAddress, txtContact.ToString, cCountry)
'Create a customers Dictionary to store the Customer.
Customers.customerDict.Add(Customers.getCustomerID, Customers)
'Close the add customer form
Me.Close()
End Sub
End Class
答案 0 :(得分:0)
想出来。
在Customer Class中,我将字典的声明更改为public shared。此外,而不是使用静态为变量增加。我将它设为Private Shared并将其移出函数和类声明区域
Public Class Customers
'Create a dictionary to hold the new customer
Public Shared customerDict As New Dictionary(Of Integer, Customers)
Private Shared cIdKey As Integer = 0