我想知道你有没有任何关于如何调试以下XML反序列化的技巧?我无法让它工作。反序列化器基本上创建了召唤和斜杠实例,但它们所有的属性都是空的。相关的类如下所示。
带有反序列化器的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从另一个类中调用:
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),并能够通过它们的属性分别访问它们。
感谢您在调试方面提供的任何帮助/提示。
DataContractSerializer
不是我的首选。它有很多陷阱,例如它要求属性在xml中按字母顺序排列。请改用XmlSerializer
。 - Mike Zboray