2010-10-26 41 views
1

我有一个类能够在我的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事件中看到这种行为?

+0

是否命名空间需要在任何地方定义的? – brumScouse 2010-10-26 18:31:21

+1

你确定它实际上试图加载相同的文件吗? – 2010-10-26 18:33:58

+0

@brumScouse不是我所知道的。 @Jon Skeet在加载事件和之后的执行过程是相同的;据我所知,这是相同的文件 – bradenb 2010-10-26 18:59:24

回答

0

@Jon Skeet走在正确的轨道上。直到我的应用程序完全加载后,我才改变当前的工作目录,所以找不到文件。

非常神秘异常,当它只是应该已经FileNotFoundException

相关问题