c# – 如何调试XML反序列化?
作者:互联网
我想知道你是否有关于如何调试以下XML反序列化的任何提示?我无法让它发挥作用.反序列化器基本上创建了summon和slash实例,但它们的所有属性都是空的.相关课程如下所示.
带反序列化器的SkillCollection类:
[DataContract(Name = "Skills", Namespace = "")]
public class SkillCollection
{
[DataMember(Name = "Slash")]
public Skill Slash { get; set; }
[DataMember(Name = "Summon")]
public Skill Summon { get; set; }
public static object Deser(string path, Type toType)
{
var s = new DataContractSerializer(toType);
using (FileStream fs = File.Open(path, FileMode.Open))
{
object s2 = s.ReadObject(fs);
if (s2 == null)
Console.WriteLine(@" Deserialized object is null");
else
Console.WriteLine(@" Deserialized type: {0}", s2.GetType());
return s2;
}
}
它是从另一个类通过属性技能调用的:
Skills = (SkillCollection)SkillCollection.Deser(
Path.Combine(path, "Skills.xml"),
typeof(SkillCollection));
技能课程:
public class Skill
{
//Cast: time it takes to cast it
[DataMember(Name = "Cast")]
public float Cast { get; set; }
//ReCast: cooldown period before player can cast it again
[DataMember(Name = "ReCast")]
public float ReCast { get; set; }
[DataMember(Name = "MPCost")]
public int MpCost { get; set; }
public Timer Timer { get; private set; }
public bool Ready { get; set; }
public Skill()
{
Ready = true;
Timer = new Timer { Interval = ReCast + 500, AutoReset = false };
Timer.Elapsed += OnTimedEvent;
}
//Runs when recast is up
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
Ready = true;
}
}
XML文件:
<Skills>
<Slash>
<Cast>0.00</Cast>
<ReCast>60.00</ReCast>
<MPCost>0</MPCost>
</Slash>
<Summon>
<Cast>5.98</Cast>
<ReCast>2.49</ReCast>
<MPCost>0</MPCost>
</Summon>
</Skills>
这样就没有混淆,我的目标是运行反序列化器,然后让SkillCollection类包含两个Skill(Slash和Summon)实例,并能够通过它们的属性分别访问它们.
感谢您提供有关调试的任何帮助/提示.
解决方法:
安德斯
我最近做了类似的任务.看看你的代码,你似乎设置了DataContract Name和Namespace错误.要在Skill类和SkillCollection类之上指定:[DataContract(Name =“Skills”,Namespace =“”)].这对于“允许”进入属性的序列化程序至关重要.请记住,仅将其设置在SkillCollection类之上是不够的.
编辑:我最初认为你可以省略命名空间,但你不能.它必须设置为Namespace =“”,如果您没有在XML中指定命名空间,或者您指定命名空间的任何内容,在您指定它的情况下.
此外,调试它的方法是将Deser方法更改为:
public static object Deserialize(string path, Type toType)
{
using (var sr = new FileStream(path, FileMode.Open))
{
SkillCollection p = null;
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(sr, new XmlDictionaryReaderQuotas());
var serializer = new DataContractSerializer(toType);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (serializer.IsStartObject(reader))
{
Console.WriteLine(@"Found the element");
p = (SkillCollection)serializer.ReadObject(reader);
Console.WriteLine("{0} {1} id:{2}",
p.Slash.ToString(), p.Summon.ToString());
}
Console.WriteLine(reader.Name);
break;
}
}
return p;
}
}
标签:c,serialization,xml,xml-deserialization 来源: https://codeday.me/bug/20190708/1403485.html