C# 如何序列化从列表继承的类<;T>;是否将自定义参数转换为XML?
我有一个从列表继承的类C# 如何序列化从列表继承的类<;T>;是否将自定义参数转换为XML?,c#,xml,unity3d,C#,Xml,Unity3d,我有一个从列表继承的类 [Serializable] public class ListWithVersion<T> : List<T> { [XmlElement(ElementName = "version")] public int version; public ListWithVersion(IEnumerable<T> collection) : base(collection) { } publ
[Serializable]
public class ListWithVersion<T> : List<T>
{
[XmlElement(ElementName = "version")]
public int version;
public ListWithVersion(IEnumerable<T> collection) : base(collection)
{
}
public ListWithVersion() : base()
{
}
}
在XML中获取版本参数没有任何帮助
那么我该如何修复它呢?您将无法直接这样做,因为
XmlSerializer
对ICollection
对象有一个特殊的处理,它(正如您所注意到的)几乎忽略了类,只是序列化了它的内容。两种选择:
- 实现
并执行您自己的序列化IXmlSerializable
- 修改类,使其具有类型为
的成员,而不是从中继承List
列表
IList
,而不是List
。使用私有列表实现所有接口成员,例如:IXmlSerializable
——首先编写自己的变量,然后使用私有列表输出所有其他内容您不能直接这样做,因为
XmlSerializer
对ICollection
对象有一个特殊的处理,它(正如您所注意到的)几乎忽略了类,只是序列化了它的内容。两种选择:
- 实现
并执行您自己的序列化IXmlSerializable
- 修改类,使其具有类型为
的成员,而不是从中继承List
列表
IList
,而不是List
。使用私有列表实现所有接口成员,例如:IXmlSerializable
——首先编写自己的变量,然后使用私有列表输出所有其他内容我能不能先写版本参数的值,然后使用默认ICollection的实现方式来实现它?@user2686299更新了我的答案我能不能先写版本参数的值,然后使用默认ICollection的实现方式来实现它?@user2686299更新了我的答案
ListWithVersion<Chapter> lwv = new ListWithVersion<Chapter>();
Chapter chapter = new Chapter();
chapter.dialogs = new List<Dialog>();
lwv.version = 1;
lwv.Add(chapter);
Serialize("lwv.xml", typeof(ListWithVersion<Chapter>), extraTypes, lwv);
private void Serialize(string name, Type type, Type[] extraTypes, object obj)
{
try
{
var serializer = new XmlSerializer(type, extraTypes);
using (var fs = new FileStream(GetPathSave() + name, FileMode.Create, FileAccess.Write))
{
serializer.Serialize(fs, obj);
}
}
catch (XmlException e)
{
Debug.LogError("serialization exception, " + name + " Message: " + e.Message);
}
catch (System.Exception ex)
{
Debug.LogError("exc while ser file '" + name + "': " + ex.Message);
System.Exception exc = ex.InnerException;
int i = 0;
while (exc != null)
{
Debug.LogError("inner " + i + ": " + exc.Message);
i++;
exc = exc.InnerException;
}
}
}
<?xml version="1.0" encoding="windows-1251"?>
<ArrayOfChapter xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Chapter id="0">
<dialogs />
</Chapter>
</ArrayOfChapter>
public int version;
public void Add(T item) => this.list.Add(item);
public void Clear() => this.list.Clear();
[...]