C# WPF中的XMLSerialization问题
假设我有以下课程:C# WPF中的XMLSerialization问题,c#,wpf,xaml,xml-serialization,C#,Wpf,Xaml,Xml Serialization,假设我有以下课程: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NetworkSwitcher { [Serializable] class testClass { public string str; public testClass(string _str) {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetworkSwitcher
{
[Serializable]
class testClass
{
public string str;
public testClass(string _str)
{
this.str = _str;
}
}
}
现在,当我尝试执行以下操作时,它抛出System.Windows.Markup.XamlParseException
testClass tc = new testClass("Hello World");
XmlSerializer xsl = new XmlSerializer(typeof(testClass));
TextWriter WriteFileStream = new StreamWriter(@"C:\NSProfiles.xml");
xsl.Serialize(WriteFileStream, tc);
WriteFileStream.Close();
如果我使用一个简单的字符串类型对象而不是tectClass,那么代码可以正常工作:
string data = "hello world";
XmlSerializer xsl = new XmlSerializer(typeof(String));
TextWriter WriteFileStream = new StreamWriter(@"C:\NSProfiles.xml");
xsl.Serialize(WriteFileStream, data);
WriteFileStream.Close();
所以我猜问题出在类定义中,我如何修复它?我使用的是WPF,而不是WinForms,而且我在WPF或XMLSerialization方面没有任何经验。请告诉我是否需要提供任何其他有用的信息。开始阅读有关Xml序列化的文档 你错过了:
- 字符串的公共属性
- Xml序列化的所有属性都将正常工作
NLO不确定您的XAML异常来自何处,但是,这一个毫无意义。开始阅读有关Xml序列化的文档 你错过了:
- 字符串的公共属性
- Xml序列化的所有属性都将正常工作
NLO不确定XAML异常来自何处,但是,这一个没有意义。要修复错误,请向类添加默认构造函数(不带参数的构造函数) 单独执行此操作将阻止错误发生,但可能无法正确序列化字符串值。我不是100%确定,因为它可能能够序列化一个公共成员变量 如果没有,则需要为字符串值添加公共属性 此类的更“标准”的实现可能如下所示。您可以使用第二个构造函数,也可以使用setter来设置值:
[Serializable]
public class testClass
{
private string str;
public testClass()
{
}
public string Str
{
get { return str; }
set { str = value; }
}
}
编辑:将公共修饰符添加到类中。现在应该可以工作了
另外,我猜您正在调用在窗口的构造函数中抛出异常的代码?这是我看到这会引发XAML异常的唯一原因。构造函数中的错误被包装在该XAML异常中,因此在这些情况下,您希望查看InnerException以找到问题 若要修复错误,请向类添加默认构造函数(不带参数的构造函数) 单独执行此操作将阻止错误发生,但可能无法正确序列化字符串值。我不是100%确定,因为它可能能够序列化一个公共成员变量 如果没有,则需要为字符串值添加公共属性 此类的更“标准”的实现可能如下所示。您可以使用第二个构造函数,也可以使用setter来设置值:
[Serializable]
public class testClass
{
private string str;
public testClass()
{
}
public string Str
{
get { return str; }
set { str = value; }
}
}
编辑:将公共修饰符添加到类中。现在应该可以工作了
另外,我猜您正在调用在窗口的构造函数中抛出异常的代码?这是我看到这会引发XAML异常的唯一原因。构造函数中的错误被包装在该XAML异常中,因此在这些情况下,您希望查看InnerException以找到问题 这些解决了问题
- 在类的顶部添加[Serializable()]
- 添加默认构造函数
- 向类添加公共类修饰符
using System; using System.Linq; using System.Text; using System.Collections.Generic; namespace NetworkSwitcher { [Serializable()] public class testClass { private string str; public string _str { get { return str; } set { str = value; } } public testClass() { //Default } } }
- 在类的顶部添加[Serializable()]
- 添加默认构造函数
- 向类添加公共类修饰符
using System; using System.Linq; using System.Text; using System.Collections.Generic; namespace NetworkSwitcher { [Serializable()] public class testClass { private string str; public string _str { get { return str; } set { str = value; } } public testClass() { //Default } } }
- 这些解决了问题