我在将信息反序列化为单例类时遇到了一点问题。
这是我目前的设置:
[XmlRoot("Root")]
public class SerializeTwoClasses
{
ClassA _classA = ClassA.ClassAInstance;
ClassB _classB = ClassB.ClassBInstance;
public ClassA ClassAProp { get { return _classA; } set { _classA = value; } }
public ClassB ClassBProp { get { return _classB; } set { _classB = value; } }
}
[XmlRoot("ClassARoot")]
public class ClassA
{
static private ClassA _classA;
static public ClassA ClassAInstance
{
get
{
if(_classA == null)
_classA = new ClassA();
return _classA;
}
}
public int Id { get; set; }
public string Value { get; set; }
public Address Address { get; set; }
}
[XmlRoot("ClassBRoot")]
public class ClassB
{
static private ClassB _classB;
static public ClassB ClassBInstance
{
get
{
if(_classB == null)
_classB = new ClassB();
return _classB;
}
}
public int IdAndereClasse { get; set; }
public string ValueAndereClasse { get; set; }
}
这就是我设置值和序列化的方式。
SerializeTwoClasses _serializeTwoClasses = new SerializeTwoClasses();
_serializeTwoClasses.ClassBProp = new ClassB { IdAndereClasse = 753951, ValueAndereClasse = "Olla" };
_serializeTwoClasses.ClassAProp.Id = 789456;
_serializeTwoClasses.ClassAProp.Value = "The Title yo";
_serializeTwoClasses.ClassAProp.Address = new Address { City = "Amsterdam", HouseNo = 1, StreetName = "Some Street" };
var serializer = new XmlSerializer(typeof(SerializeTwoClasses));
var fileStream = new System.IO.StreamWriter("serialized.config");
serializer.Serialize(fileStream, _serializeTwoClasses);
fileStream.Close();
文件中的输出是:
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ClassAProp>
<Id>789456</Id>
<Value>The Title yo</Value>
<Address>
<HouseNo>1</HouseNo>
<StreetName>Some Street</StreetName>
<City>Amsterdam</City>
</Address>
</ClassAProp>
<ClassBProp>
<IdAndereClasse>753951</IdAndereClasse>
<ValueAndereClasse>Olla</ValueAndereClasse>
</ClassBProp>
</Root>
现在我想将文件中的信息反序列化到类中,并尝试如下:
SerializeTwoClasses _serializeTwoClasses = new SerializeTwoClasses();
XmlSerializer deserializer = new XmlSerializer(typeof(SerializeTwoClasses));
TextReader reader = new StreamReader("serialized.config");
object obj = deserializer.Deserialize(reader);
_serializeTwoClasses = (SerializeTwoClasses)obj;
reader.Close();
当我检查 _serializeTwoClasses 对象时,我可以看到 _ClassA 和 _ClassB 属性,它们代表在 serialized.config 文件中设置的值。但是...虽然 ClassA 和 ClassB 类仅通过单例方法被引用创建<我希望这两个类都用文件中的值填充。但他们不是...
在我的表单类中(我通过一个按钮触发上述序列化和反序列化方法)我在类中有这些字段:
ClassA _classA = ClassA.ClassAInstance;
ClassB _classB = ClassB.ClassBInstance;
(在序列化和反序列化之前设置)并且两个类的内容都代表了属性的默认值(0、null等)。我在看什么???
顺便说一句:由于框架中的设置,属性类需要是单例类。亲切的问候,
马蒂斯