我有3節課。第一個存盤資訊,第二個將資訊分配給第一個類,第三個從第一個類中讀取資訊。
第一類,未分配給任何 WPF 視窗
public class ProfileInfo //Used to store Name and Surname Data
{
public string User_Name { get; set; }
public string User_Surname { get; set; }
}
第二類,位于 WPF 視窗 1
public class InsertInfo //Reads data and stores it in Class 1
{
ProfileInfo p = new ProfileInfo();
p.User_Name = "Bob"; //Example value but normally is read from db
p.User_Surname = "Jhones"; //Example value but normally is read from db
}
第三類,位于 WPF 視窗 2
public class ReadInfo //Reads data from Class 1 and displays it using MessageBox.Show
{
ProfileInfo p = new ProfileInfo();
MessageBox.Show(p.User_Name); // I want this to display Bob but it displays an empty value
MessageBox.Show(p.User_Surname);
}
我希望 Class 1 存盤資訊,直到我結束程式,以便我可以檢索多個類中的資料。
據我所知,這不起作用,因為在第 3 類中,我呼叫了一個完全不同的第 1 類實體,其中沒有存盤資料???如果是這樣,我該如何進行這項作業?
我已經在互聯網上尋找一種在類之間共享資料的方法,但一切似乎都如此困難且無法理解。我是初學者,所以如果可能的話,請嘗試用不太專業的語言來解釋它。
uj5u.com熱心網友回復:
問題是你ProfileInfo 在 你的InsertInfo類中創建了一個實體,但在第三個類中ReadInfo,你創建了另一個ProfileInfo默認為空的實體。我不知道您的系統的詳細資訊,但您可以嘗試ProfileInfo將InsertInfo類中的欄位設為靜態屬性,然后您可以從其他類訪問它:
public class InsertInfo
{
private static ProfileInfo p = new ProfileInfo();
public static ProfileInfo P { get { return p; } }
public void AssignProfileInfo(string username, string surname)
{
p.User_Name = username;
p.User_Surname = surname;
}
}
然后,要訪問存盤的 ProfileInfo,您可以訪問靜態屬性:
public class ReadInfo
{
ProfileInfo p = InsertInfo.P;
public void ShowInfo()
{
MessageBox.Show(p.User_Name);
MessageBox.Show(p.User_Surname);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388105.html
