[英]XML Deserialization inside class
I tried XML serialization the first time. 我第一次尝试了XML序列化。 The following code works as expected, but I don't like to use this "copyFrom" method. 以下代码按预期工作,但我不喜欢使用此“copyFrom”方法。
Is there a better way that keeps the save and load methods inside the class itself? 有没有更好的方法将保存和加载方法保存在类本身中?
namespace Test
{
[Serializable]
public class Settings
{
public struct Connection
{
[XmlAttribute ("user")]
public string sUser;
[XmlAttribute ("domain")]
public string sDomain;
}
public Connection connection;
public Settings ()
{
connection.sUser = "";
connection.sDomain = "";
}
internal void loadFromFile ()
{
if (File.Exists (Constants.STORAGE_SETTINGS_FILE))
{
using (FileStream filestream = new FileStream (Constants.STORAGE_SETTINGS_FILE, FileMode.Open, FileAccess.Read, FileShare.Read))
{
copyFrom ((Settings)new XmlSerializer (typeof (Settings)).Deserialize (filestream));
}
}
}
internal void saveToFile ()
{
using (StreamWriter streamwriter = new StreamWriter (Constants.STORAGE_SETTINGS_FILE))
{
new XmlSerializer (typeof (Settings)).Serialize (streamwriter, this);
}
}
internal void copyFrom (Settings settings)
{
connection.sUser = settings.connection.sUser;
connection.sDomain = settings.connection.sDomain;
}
}
}
You can remove copyFrom
method. 您可以删除copyFrom
方法。
In the loadFromFile
method, you can write 在loadFromFile
方法中,您可以编写
connection = ((Settings)new XmlSerializer(typeof(Settings)).Deserialize(filestream)).connection;
Also note that the Serializable
attribute not needed for XML serialization. 另请注意,XML序列化不需要Serializable
属性。 Remove it. 去掉它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.