我正在使用Visual Studio創建Windows Forms C#項目,並試圖設置一個類型類的數組,並讓數組中的條目對應於構造函數字符串爲班級。我正在使用具有變量索引的數組,每次將新的類實例添加到數組時都會增加該數組。如何設置類數組中的類值
我遇到了索引調用超出數組邊界的問題。另外,我不確定是否爲每個實例設置了我的類變量。任何人都可以將我指向正確的方向嗎?下面是我的代碼:
public partial class MainMenu : Form
{
//int that will be used to alter the index of the array
public static int acctcount = 1;
//array of class Account
Account[] accounts = new Account[acctcount];
public MainMenu()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//check through each element of the array
for (int i = 0; i < accounts.Length; i++)
{
string stringToCheck = textBox1.Text;
foreach(Account x in accounts)
{
//check to see if entered name matches any element in the array
if (x.Name == stringToCheck)
{
//set variables in another form so that we are using the class variables for only that class
Variables1.selectedAccount = x.Name;
//is this calling the CheckBalance of the instance?
Variables1.selectedCheckBalance = Account.CheckBalance;
//same thing?
Variables1.selectedSaveBalance = Account.SaveBalance;
//switch to form
AccountMenu acctMenu = new AccountMenu();
this.Hide();
acctMenu.Show();
}
else
{
/*insert new instance of Account
the index element should be 0, since acctcount is set to 1
and we are subtracting 1 from the acctcount
we are using the string from the textbox1.Text as the constructor
for the new instance*/
accounts [acctcount-1] = new Account(stringToCheck);
//increase the index of the array by 1
acctcount += 1;
}
}
}
}
}
class Account
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private static int acctNum = 0;
public static int AcctNumber
{
get
{
return acctNum;
}
set
{
acctNum = value;
}
}
//initialize the CheckBalance value to 100.00
private static decimal checkBalance = 100.00M;
public static decimal CheckBalance
{
get
{
return checkBalance;
}
set
{
checkBalance = value;
}
}
public Account(string Name)
{
this.Name = Name;
}
private static decimal saveBalance = 100.00M;
public static decimal SaveBalance
{
get
{
return saveBalance;
}
set
{
saveBalance = value;
}
}
}
另外,您可能希望「Account」類中的屬性爲實例屬性,而不是靜態屬性... – 2014-09-27 21:25:12
是否有您使用數組而不是List的原因? – 2014-09-27 21:44:34