我正在讀一本關於序列化的書。我對實現類的部分感到困惑,或者簡單地說我並不真正理解類(可能)。把實現類困惑到xml序列化中
基本上我有我的應用程序設計用這種方式遵循我的書的步驟。我只是不理解FileSaving的類,也許在哪裏實現它。我想開始使用序列化來保存表單的元素,並使用「保存」和「加載」按鈕通過xml重新加載它。我有一個文本框和用戶鍵入字符串到Majorversiontextbox中,然後這個textbox.text被存儲爲MajorversionLabel。請澄清我的疑惑,並幫助我完成序列化。謝謝!我會澄清對我的問題的任何懷疑。
編輯
問題1,爲什麼我需要的時候,我只從標籤內容獲取值,並將其保存到一個XML文件,該FileSaving類。問題2,我的FileSaving類是否正確聲明?問題3,爲什麼我需要Get和Set over?
public partial class Window1 : Window
{
...
...
public class FileSaving
{
private string major;
public string Majorversion
{
get
{
return major;
}
set
{
major = value;
}
}
}
private void MajorversionupdateButton_Click(object sender, RoutedEventArgs e)
{
MajorversionresultLabel.Content = MajorversionTextBox.Text;
MajorversionupdateButton.Visibility = Visibility.Hidden;
MajorversionTextBox.Visibility = Visibility.Hidden;
MajorversionmodifyButton.Visibility = Visibility.Visible;
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string savepath;
SaveFileDialog DialogSave = new SaveFileDialog();
// Default file extension
DialogSave.DefaultExt = "txt";
// Available file extensions
DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
// Adds a extension if the user does not
DialogSave.AddExtension = true;
// Restores the selected directory, next time
DialogSave.RestoreDirectory = true;
// Dialog title
DialogSave.Title = "Where do you want to save the file?";
// Startup directory
DialogSave.InitialDirectory = @"C:/";
DialogSave.ShowDialog();
savepath = DialogSave.FileName;
DialogSave.Dispose();
DialogSave = null;
Filesaving abc = new FileSaving();
abc.Majorversion = MajorversionLabel.Content;
FileStream savestream = new FileStream(path, FileMode.Create);
XmlSerializer serializer = new XmlSerializer(typeof(FileSaving));
serializer.Serialize(savestream, abc);
}
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
string loadpath;
Stream checkStream = null;
Microsoft.Win32.OpenFileDialog DialogLoad = new Microsoft.Win32.OpenFileDialog();
DialogLoad.Multiselect = false;
DialogLoad.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
if ((bool)DialogLoad.ShowDialog())
{
try
{
if ((checkStream = DialogLoad.OpenFile()) != null)
{
loadpath = DialogLoad.FileName;
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
else
{
System.Windows.MessageBox.Show("Problem occured, try again later");
}
FileSaving abc = new FileSaving();
FileStream loadstream = new FileStream(loadpath, FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(FileSaving));
abc=(FileSaving)serializer.Deserialize(loadstream);
loadstream.Close();
MajorversionresultLabel.Content = abc.Majorversion;
}
}
有問題嗎? – 2011-02-23 06:45:08
@Marc Gravell請參閱編輯 – jeremychan 2011-02-23 06:53:47