[英]Homework find matching object in a list of objects and access properties of that object
我正在嘗試創建一個模仿ATM的程序。 在我的程序中,我需要檢查用戶輸入的字符串是否與對象列表中任何對象的Name屬性匹配。 如果不匹配,則會自動為該帳戶添加一些其他默認值。 如果確實匹配,那么我需要將在另一個表單上訪問的變量設置為該帳戶對象的屬性。 此外,這些屬性將需要從其他形式更新,以便使對象保持最新狀態。 我認為我可以弄清楚如何更新這些屬性,但是在嘗試將變量設置為當前帳戶時遇到了困難,更具體地說,是如何訪問匹配帳戶的屬性。 我的類構造函數如下:
class Account
{
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
private int acctNum = 0;
public int AcctNumber
{
get
{
return acctNum;
}
set
{
acctNum = value;
}
}
//initialize the CheckBalance value to 100.00
private decimal checkBalance = 100.00M;
public decimal CheckBalance
{
get
{
return checkBalance;
}
set
{
checkBalance = value;
}
}
public Account(string Name)
{
this.Name = Name;
}
private decimal saveBalance = 100.00M;
public decimal SaveBalance
{
get
{
return saveBalance;
}
set
{
saveBalance = value;
}
}
}
這樣做很好,因為我唯一需要的構造函數是Name屬性,而其他屬性會自動設置為基值。 我當前擁有的列表和相關代碼如下:
//variable that will be used to check textbox1.Text
string stringToCheck;
//array of class Account
List<Account> accounts= new List<Account>();
public MainMenu()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//set value to user's input
stringToCheck = textBox1.Text;
//set a var that only returns a value if the .Name already exists
var matches = accounts.Where(p => p.Name == stringToCheck);
//check through each element of the array
if (!accounts.Any())
{
accounts.Add(new Account(stringToCheck));
}
else if (matches != null)
//set variables in another form. not sure if these are working
Variables1.selectedAccount = ;
//is this calling the CheckBalance of the instance?
Variables1.selectedCheckBalance = accounts[i].CheckBalance;
//same thing?
Variables1.selectedSaveBalance = accounts[i].SaveBalance;
//switch to form
AccountMenu acctMenu = new AccountMenu();
this.Hide();
acctMenu.Show();
}
在上面的代碼中,“ else if(matches!= null)”更像是填充符,因為我不確定該使用什么。 當然,我還需要重新編寫“ if(!accounts.Any())”部分,因為一旦列表中至少填充了一個對象,此代碼將不再發生。 因此,實際上,我只需要知道如何檢查匹配的帳戶以及如何訪問該帳戶的屬性,就可以將Variables1屬性設置為匹配。 謝謝你的幫助!
如果它適合您的特定情況,則var account = accounts.FirstOrDefault(p => p.Name == stringToCheck)
將為您提供集合中與該表達式匹配的第一個帳戶,如果不存在則為null。
檢查account != null
是否確保嘗試get
屬性值時不會出現null引用異常。
然后,使用account.CheckBalance
獲取該特定帳戶的屬性值。
我可能沒有完全理解這個問題,因此無法發表評論,因為我沒有50的聲譽:(
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.