我有一個類能夠在我的WPF應用程序加載後輕鬆地序列化和反序列化。我現在試圖添加在傳入項目文件時啓動時加載項目的功能。不幸的是,它拋出一個InvalidOperationException聲明:反序列化導致在啓動時加載時出現InvalidOperationException
There is an error in XML document (2, 2). ---> System.InvalidOperationException: <WeightingParametersBit xmlns=''> was not expected.
的WeightingParametersBit
是類我試圖序列化的成員的類型。它基本上只是一個字典的容器。奇怪的是,該文件不包含文件中任何位置的<WeightingParametersBit xmlns=....
的標籤。一旦拋出異常並且應用程序啓動。如果我點擊加載按鈕並選擇相同的項目文件,它加載得很好。
這裏是我試圖序列化類(小容器類):
public class WeightSettings
{
public double UserScoreSlagging;
public double UserScoreFouling;
public WeightMode BitWeightMode = WeightMode.Manual;
public WeightMode LigWeightMode = WeightMode.Manual;
public WeightingParametersBit BitWeights = new WeightingParametersBit();
public WeightingParametersLig LigWeights = new WeightingParametersLig();
}
這裏是它生成的XML(下調以便查看):
<?xml version="1.0" encoding="utf-8"?>
<WeightSettings>
<UserScoreSlagging>0</UserScoreSlagging>
<UserScoreFouling>0</UserScoreFouling>
<BitWeightMode>Manual</BitWeightMode>
<LigWeightMode>Manual</LigWeightMode>
<BitWeights>
<bituminous>
...
</bituminous>
</BitWeights>
<LigWeights>
<lignitic>
...
</lignitic>
</LigWeights>
</WeightSettings>
我一般序列代碼:
public static void Serialize<T>(this T source, TextWriter writer)
{
// Don't serialize a null object
if (Object.ReferenceEquals(source, null))
{
throw new ArgumentException("Trying to serialize null object.", "source");
}
XmlSerializer s = new XmlSerializer(typeof(T));
s.Serialize(writer, source);
writer.WriteLine();
}
和反序列化代碼:
public static T Deserialize<T>(this T source, TextReader reader)
{
XmlSerializer s = new XmlSerializer(typeof(T));
source = (T)s.Deserialize(reader);
return source;
}
調用反序列化是從一個叫WeightSettings
(的WeightSettings
型)財產不爲空:
WeightSettings = WeightSettings.Deserialize(sr);
我怎樣才能解決這個問題?也許更重要的是:爲什麼我只在Window Loaded事件中看到這種行爲?
是否命名空間需要在任何地方定義的? – brumScouse 2010-10-26 18:31:21
你確定它實際上試圖加載相同的文件嗎? – 2010-10-26 18:33:58
@brumScouse不是我所知道的。 @Jon Skeet在加載事件和之後的執行過程是相同的;據我所知,這是相同的文件 – bradenb 2010-10-26 18:59:24