我想知道是否有比我下面显示的更直接/更优雅的方式,从XML文件中获取数据并从中创建自定义类的实例。以下是我目前的做法(有效,但可能有点笨拙)。
我的XML:
<Skills>
<Fire>
<Cast>0.00</Cast>
<ReCast>90.00</ReCast>
<MPCost>0</MPCost>
<Button>8</Button>
</Fire>
<Ice>
<Cast>5.98</Cast>
<ReCast>2.49</ReCast>
<MPCost>0</MPCost>
<Button>9</Button>
</Ice>
</Skills>
1)将XML中的元素加载到词典中
//Load Skill list
var skillXElement = XDocument.Load(path + @"\Skills.xml").Root;
if (skillXElement != null)
SkillDictionary =
skillXElement.Elements()
.ToDictionary(e => e.Name.LocalName,
e =>
new Skill(e.Name.LocalName, (double) e.Element("Cast"), (double) e.Element("ReCast"),
(int) e.Element("MPCost"), e.Element("Button").Value[0]));
2)根据词典创建对技能类的引用:
class SkillInfo
{
public Skill Fire { get; private set; }
public Skill Ice { get; private set; }
public SkillInfo()
{
Fire = Globals.Instance.SkillDictionary["Fire"];
Ice= Globals.Instance.SkillDictionary["Ice"];
}
}
3)最后,我通过公共财产获取技能:
class Player : Character
{
public Player()
{
SkillInfo = new SkillInfo();
}
public SkillInfo SkillInfo { get; private set; }
private ExampleMethod()
{
UseSkill(SkillInfo.Fire);
}
}
您可能想知道我为什么不直接从词典中访问每个技能:UseSkill(Globals.Instance.SkillDictionary["Fire"]);
。原因是字典中的每个查找都相当慢(大约500毫秒),尽管是O(1)。因此,为了避免每次使用技能时出现延迟,我创建了SkillInfo类。
如何更优雅地从XML到类实例的任何提示或想法都将受到高度赞赏。
提前致谢!
编辑:请求下方的其他信息
答案 0 :(得分:1)
只需将MemoryStream
替换为StreamReader
即可从文件中读取:
void Main()
{
var xml = @"<Skills>
<Fire>
<Cast>0.00</Cast>
<ReCast>90.00</ReCast>
<MPCost>0</MPCost>
<Button>8</Button>
</Fire>
<Ice>
<Cast>5.98</Cast>
<ReCast>2.49</ReCast>
<MPCost>0</MPCost>
<Button>9</Button>
</Ice>
</Skills>";
using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
var serializer = new XmlSerializer(typeof(Skills));
var skills = (Skills)serializer.Deserialize(memoryStream);
// good to go!
}
}
public class Skill
{
public double Cast { get; set; }
public double ReCast { get; set; }
public int MPCost { get; set; }
public int Button { get; set; }
}
public class Skills
{
public Skill Fire { get; set; }
public Skill Ice { get; set; }
}