gpt4 book ai didi

c# - Linq to xml,检索基于通用接口(interface)的列表

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:12 24 4
gpt4 key购买 nike

我有一个看起来像这样的 XML 文档

    <Elements>
<Element>
<DisplayName />
<Type />
</Element>
</Elements>

我有一个接口(interface),

interface IElement
{
string DisplayName {get;}
}

和几个派生类:

public class AElement: IElement

public class BElement: IElement

我想做的是编写最有效的查询来遍历 XML 并创建 IElement 的列表。 , 包含 AElementBElement ,基于 XML 中的“类型”属性。

到目前为止我有这个:

IEnumerable<AElement> elements = 
from xmlElement in XElement.Load(path).Elements("Element")
where xmlElement.Element("type").Value == "AElement"
select new AElement(xmlElement.Element("DisplayName").Value);

return elements.Cast<IElement>().ToList();

但这仅适用于 AElement .有没有办法添加 BElement在同一个查询中,并将其设为通用 IEnumerable<IElement> ?或者我是否必须为每个派生类型运行一次此查询?

最佳答案

您可以使用条件运算符:

IEnumerable<IElement> elements = 
from xmlElement in XElement.Load(path).Elements("Element")
let type = (string)xmlElement.Element("Type")
let name = (string)xmlElement.Element("DisplayName")
select type == "AElement"
? (IElement)new AElement(name)
: (IElement)new BElement(name);

或者,使用常规语法:

IEnumerable<IElement> elements =
XElement.Load(path)
.Elements("Element")
.Select(xmlElement =>
{
var type = (string)xmlElement.Element("Type");
var name = (string)xmlElement.Element("DisplayName");

switch (type)
{
case "AElement": return (IElement)new AElement(name);
case "BElement": return (IElement)new BElement(name);
}

throw new Exception();
});

关于c# - Linq to xml,检索基于通用接口(interface)的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2952047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com