我的课:
public class Device
{
int ID;
string Name;
List<Function> Functions;
}
Run Code Online (Sandbox Code Playgroud)
和类功能:
public class Function
{
int Number;
string Name;
}
Run Code Online (Sandbox Code Playgroud)
我有这个结构的xml文件:
<Devices>
<Device Number="58" Name="Default Device" >
<Functions>
<Function Number="1" Name="Default func" />
<Function Number="2" Name="Default func2" />
<Function Number="..." Name="...." />
</Functions>
</Device>
</Devices>
Run Code Online (Sandbox Code Playgroud)
这是代码,我正在尝试读取对象:
var list = from tmp in document.Element("Devices").Elements("Device")
select new Device()
{
ID = Convert.ToInt32(tmp.Attribute("Number").Value),
Name = tmp.Attribute("Name").Value,
//??????
};
DevicesList.AddRange(list);
Run Code Online (Sandbox Code Playgroud)
我怎么读"功能"???
再做同样的事情,使用Elements和Select将一组元素投影到对象.
var list = document
.Descendants("Device")
.Select(x => new Device {
ID = (int) x.Attribute("Number"),
Name = (string) x.Attribute("Name"),
Functions = x.Element("Functions")
.Elements("Function")
.Select(f =>
new Function {
Number = (int) f.Attribute("Number"),
Name = (string) f.Attribute("Name")
}).ToList()
});
Run Code Online (Sandbox Code Playgroud)
为清楚起见,我实际上建议FromXElement在每个Device和中写一个静态方法Function.然后每一段代码都可以做一件事.例如,Device.FromXElement可能看起来像这样:
public static Device FromXElement(XElement element)
{
return new Device
{
ID = (int) element.Attribute("Number"),
Name = (string) element.Attribute("Name"),
Functions = element.Element("Functions").Elements("Function")
.Select(Function.FromXElement)
.ToList();
};
}
Run Code Online (Sandbox Code Playgroud)
这也允许您在类中使setter私有,因此它们可以是公共不可变的(在集合周围稍作努力).
| 归档时间: |
|
| 查看次数: |
478 次 |
| 最近记录: |