[英]Accessing a variable from another class c#
因此,場景是用戶已經使用憑據登錄,並且當他們將商品添加到購物車時,我希望將全名從Account.cs
提取到ProductGUI.cs
這是我嘗試過的方法,但是會提示出一個空的Console語句。
抱歉,如果我問一個重復的問題,但我需要幫助以弄清楚如何專門解決此問題。
Account.cs
private string fullname;
private string username;
private string email;
private string password;
public Account(string fullname, string username, string email, string password)
{
this.fullname = fullname;
this.username = username;
this.email = email;
this.password = password;
}
public string Fullname
{
get
{
return fullname;
}
set
{
fullname = value;
}
}
ProductGUI.cs
private void addToCartButton_Click(object sender, EventArgs e)
{
// I believe I'm creating a new account based another question, but how do i pass the information without creating a new account.
Account a = new Account();
Console.WriteLine(a.Fullname);
}
LoginGUI.cs
private void signinButton_Click(object sender, EventArgs e)
{
bool temp = false;
foreach (DataRow row in dt.Rows)
{
if (row["Username"].ToString() == usernameTextbox.Text && row["Password"].ToString() == passwordTextbox.Text)
{
string fullname = row["Fullname"].ToString();
string username = row["Username"].ToString();
string email = row["Email"].ToString();
string password = row["Password"].ToString();
// I've saved the information into account.
acc = new Account(fullname, username, email, password);
temp = true;
}
}
if (temp)
{
MessageBox.Show("Welcome to Anime Fanatic.\n Enjoy your stay!");
this.Hide();
mainPageGUI mainPage = new mainPageGUI();
mainPage.ShowDialog();
}
else
{
MessageBox.Show("You have entered an incorrect Username or Password.\n Please try again!");
}
}
您必須使Login-GUI和Product-GUI都知道您的Account
實例。 最簡單(最丑陋,最不推薦)的方法是使其靜態:
class LoginGUI
{
public static Account acc;
[...]
}
class ProductGUI
{
private void addToCartButton_Click(object sender, EventArgs e)
{
Console.WriteLine(LoginGUI.acc.Fullname);
}
[...]
}
但是,確實,對單例模式有很好的了解。 依賴注入也可能會有所幫助。
您可以通過創建全名的靜態屬性來實現。 它們對於在程序中抽象全局數據很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.